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. [WPF,XAML] 跳动的心

    原文:[WPF,XAML] 跳动的心 没什么艺术细胞,原谅,原谅! <Canvas Width="0" Height="0"> <Canvas ...

  2. JS中的Set 与去重

    -----------------------Set 与去重----------------------- ES6 提供了新的数据结构 Set.它类似于数组,但是成员的值都是唯一的,没有重复的值.Se ...

  3. SELECT使用子查询

    SELECT使用子查询   SELECT使用子查询,该子查询会执行多次,  次数是由记录数量决定.效率比较低,不推荐使用.  //查询部门编号,工资大于等于2000的人数,  //工资小于2000的人 ...

  4. iBase4J部署总结

    iBase4J部署总结 序言 最近看到个分布式框架,只有一个字:好.所以部署起来看看.开始的时候说实话遇到了点困难.去码云上看了下,貌似想得到指导要加入一个群,而且需要收费的,反正闲来无事,索性自己搞 ...

  5. ssm框架下上传图片及其他信息

    先引入这两个包: <dependency> <groupId>commons-fileupload</groupId> <artifactId>comm ...

  6. 任务调度器quartz的使用

    1.quartz的获取. 可參照:Quartz任务调度模型实例 2.开发思路: 要使用定时器quartz.先弄清楚三个概念:调度器.任务.触发器.开发也是依照这三个方面来开发, 1>写一个Job ...

  7. h5缓存之数据库

    /*======================================================= 函数功能:保存日志到本地数据库 ========================== ...

  8. 高级程序员与CTO技术总监首席架构师

    一.高级程序员 如果你是一个刚刚创业的公司,公司没有专职产品经理和项目经理,你就是公司的产品经理,你如果对你现在的开发员能力不满,那么你只需要的是一个高级程序员. 你定义功能.你做计划推进和管理,他可 ...

  9. Cocos结构

    基类:CApplicationProtocol 纯虚函数virtual bool applicationDidFinishLaunching() = 0; CCApplication继承于CCAppl ...

  10. KMP字符串查找算法

    #include <iostream> #include <windows.h> using namespace std; void get_next(char *str,in ...