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. 阿里云Linux系统安装配置Tomcat方法

    本文将tomcat安装到了/alidata/server/目录下,当然也可以安装到其他目录. 1. 下载tomcat:#wget http://apache.fayea.com/tomcat/tomc ...

  2. HDU 5305 Friends (搜索+剪枝) 2015多校联合第二场

    開始对点搜索,直接写乱了.想了想对边搜索,尽管复杂度高.剪枝一下水过去了. 代码: #include<cstdio> #include<iostream> #include&l ...

  3. tableau desktop(三)--构建数据视图(二)

    前段时间忙于工作的事情,好久没有来记录一点东西了,今天利用周末做点记录吧,近期因为工作的原因,也有两三周没实用tableau了.今天继续上一篇构建数据试图(二). 3.7 參考线和參考区间 參考线通经 ...

  4. mysql int(m)与int(m)的差别

    预计大多数開始接触mysql的朋友们都会有这个问题:int(M) 里面的数值究竟是什么意思? 依据相关资料总结了下: int(M) zerofill,加上zerofill后M才表现出有点点效果,比方  ...

  5. C/C++数据类型的转换之终极无惑

    程序开发环境:VS2012+Win32+Debug 数据类型在编程中常常遇到.尽管可能存在风险,但我们却乐此不疲的进行数据类型的转换. 1. 隐式数据类型转换 数据类型转换.究竟做了些什么事情呢?实际 ...

  6. bzoj2150: 部落战争(匈牙利)

    2150: 部落战争 题目:传送门 题解: 辣鸡数据..毁我AC率 先说做法,很容易就可以看出是二分图匹配的最小路径覆盖(可能是之前不久刚做过类似的题) 一开始还傻逼逼的去直接连边然后准备跑floyd ...

  7. 神经网络预测mnist时候如果不归一化,则准确率仅仅10%下文作者svm也遇到了。

    转自:http://blog.csdn.net/jeryjeryjery/article/details/72649320 这两天用Python来实现手写数字识别,刚开始用原始数据进行训练,结果预测结 ...

  8. [bzoj 1398] Vijos1382寻找主人 Necklace 解题报告(最小表示法)

    题目链接:https://www.lydsy.com/JudgeOnline/problem.php?id=1398 题目: Description 给定两个项链的表示,判断他们是否可能是一条项链. ...

  9. oracle 11g rac for linux add node (oracle 11g rac 节点添加)

    说明: Adding Oracle RAC to Nodes with Oracle Clusterware Installed步骤来自ORACLE 官方文档: https://docs.oracle ...

  10. Elasticsearch之四种查询类型和搜索原理(博主推荐)

    Elasticsearch Client发送搜索请求,某个索引库,一般默认是5个分片(shard). 它返回的时候,由各个分片汇总结果回来. 官网API https://www.elastic.co/ ...