Thinking in States

Niclas Nilsson

PEOPLE IN THE REAL WORLD HAVE A WEIRD RELATIONSHIP WITH STATE.

This morning, I stopped by the local store to prepare for another day of con- verting caffeine to code. Since my favorite way of doing that is by drinking lattes, and I couldn’t find any milk, I asked the clerk.

“Sorry, we’re super-duper, mega–out of milk.”

To a programmer, that’s an odd statement. You’re either out of milk, or you’re not. There is no scale when it comes to being out of milk. Perhaps she was try- ing to tell me that they’d be out of milk for a week, but the outcome was the same—espresso day for me.

In most real-world situations, people’s relaxed attitude toward state is not an issue. Unfortunately, however, many programmers are quite vague about state, too—and that is a problem.

Consider a simple webshop that only accepts credit cards and does not invoice customers, with an Order class containing this method:

public boolean isComplete() {

return isPaid() && hasShipped();

}

Reasonable, right? Well, even if the expression is nicely extracted into a method instead of copy ’n’ pasted everywhere, the expression shouldn’t exist at all. The fact that it does highlights a problem. Why? Because an order can’t be shipped before it’s paid. Thereby, hasShipped can’t be true unless isPaid is true, which makes part of the expression redundant. You may still want isComplete for clarity in the code, but then it should look like this:

    public boolean isComplete() {
return hasShipped();
}

168

97 Things Every Programmer Should Know



In my work, I see both missing checks and redundant checks all the time. This example is tiny, but when you add cancellation and repayment, it’ll become more complex, and the need for good state handling increases. In this case, an order can only be in one of three distinct states:

• In progress: Can add or remove items. Can’t ship.

• Paid: Can’t add or remove items. Can be shipped.

• Shipped: Done. No more changes accepted.

These states are important, and you need to check that you’re in the expected state before doing operations, and that you only move to a legal state from where you are. In short, you have to protect your objects carefully, in the right places.

But how do you begin thinking in states? Extracting expressions to meaningful methods is a very good start, but it is just a start. The foundation is to under- stand state machines. I know you may have bad memories from CS class, but leave them behind. State machines are not particularly hard. Visualize them to make them simple to understand and easy to talk about. Test-drive your code to unravel valid and invalid states and transitions and to keep them correct. Study the State pattern. When you feel comfortable, read up on Design by Contract. It helps you ensure a valid state by validating incoming data and the object itself on entry and exit of each public method.

If your state is incorrect, there’s a bug, and you risk trashing data if you don’t abort. If you find the state checks to be noise, learn how to use a tool, code generation, weaving, or aspects to hide them. Regardless of which approach you pick, thinking in states will make your code simpler and more robust.

Thinking in States的更多相关文章

  1. Life Cycle of Thread – Understanding Thread States in Java

    Life Cycle of Thread – Understanding Thread States in Java 深入理解java线程生命周期. Understanding Life Cycle ...

  2. Hover States - 有趣的用户界面及交互设计

    Hover States 一组新潮的和有趣的用户界面和交互设计的集合.Hover States 的目标是要成为设计师和开发人员灵感来源,向人们展示目前人们正在做的各种网站中令人惊奇的效果.他们认为交互 ...

  3. Channel States

    Introduction A channel (a call) will go through many different states during its lifetime. Here we w ...

  4. flex4的s:states和mx:states的区别

    http://help.adobe.com/en_US/Flex/4.0/UsingSDK/WS2db454920e96a9e51e63e3d11c0bf63611-7ffa.html#WS43468 ...

  5. How to Programmatically Switch between the HubTile Visual States

    In this post I am going to talk about how to programmatically switch between different HubTile Visua ...

  6. PROCESS STATES

    COMPUTER ORGANIZATION AND ARCHITECTURE DESIGNING FOR PERFORMANCE NINTH EDITION To understand the ope ...

  7. [Angular2 Form] Understand the Angular 2 States of Inputs: Pristine and Untouched

    Angular 2’s ngModel exposes more than just validity, it even gives you the states of whether the inp ...

  8. codeforces 590C C. Three States(bfs+连通块之间的最短距离)

    题目链接: C. Three States time limit per test 5 seconds memory limit per test 512 megabytes input standa ...

  9. Codeforces Round #327 (Div. 2) E. Three States

    题目链接: 题目 E. Three States time limit per test:5 seconds memory limit per test:512 megabytes 问题描述 The ...

  10. I.MX6 show battery states in commandLine

    #/bin/sh # I.MX6 show battery states in commandLine # 声明: # 在命令行下自动显示电池状态的信息. # # -- # set battery r ...

随机推荐

  1. oracle 的列转行函数 listagg()

    当你的表X中有A,B两列,数据如下 A B a 1 a 2 a 3 b 1 b 2 b 3 想让数据以 a|1|2|3 , b|1|2|3 格式显示可使用listagg() 1.使用listagg() ...

  2. [luogu] P4823 [TJOI2013]拯救小矮人(贪心)

    P4823 [TJOI2013]拯救小矮人 题目描述 一群小矮人掉进了一个很深的陷阱里,由于太矮爬不上来,于是他们决定搭一个人梯.即:一个小矮人站在另一小矮人的 肩膀上,知道最顶端的小矮人伸直胳膊可以 ...

  3. Ural 1004 Sightseeing Trip

    Sightseeing Trip Time Limit: 2000ms Memory Limit: 16384KB This problem will be judged on Ural. Origi ...

  4. 2015 Multi-University Training Contest 4 hdu 5338 ZZX and Permutations

    ZZX and Permutations Time Limit: 6000/3000 MS (Java/Others)    Memory Limit: 131072/131072 K (Java/O ...

  5. ofbiz初级教程

    本教程是ofbiz 基本应用,它涵盖了OFBiz应用程序开发过程的基本原理.目标是使开发人员熟悉最佳实践,编码惯例,基本控制流程以及开发人员对OFBiz定制所需的所有其他方面. 本教程将帮助您在OFB ...

  6. leetcode笔记:Find Median from Data Stream

    一. 题目描写叙述 Median is the middle value in an ordered integer list. If the size of the list is even, th ...

  7. 10.2.0.4 to 10.2.0.5 Installation of Patch Set Release (Windows)

    环境:10.2.0.4集群数据库zlm10g(双节点,zlm10g1,zlm10g2) 系统:Windows 2003 Server 64Bit 内存:2G RAM 存储:ASM 目标:把集群数据库从 ...

  8. HDU 2643

    (第二类斯特林数*N的阶乘 )的和. #include <iostream> #include <cstdio> #include <algorithm> #def ...

  9. HDU 4828

    其实..这题是<组合数学>的习题中的一道......当初不会..... 想到一个证明: 填入2n个数,把填在上方的数的位置填上+1,下方的填上-1.这样,在序列1....2n的位置,任意前 ...

  10. Docker 命令行和后台參数

    Docker官方为了让用户高速了解Docker,提供了一个交互式教程,旨在帮助用户掌握Docker命令行的用法. Docker 命令行 以下对Docker的命令清单进行简单的介绍,具体内容在兴许章节具 ...