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. Django REST Framework 认证 - 权限 - 限制

    一. 认证 (你是谁?) REST framework 提供了一些开箱即用的身份验证方案,并且还允许你实现自定义方案. 自定义Token认证 第一步 : 建表>>>> 定义一个 ...

  2. webpack实战---安装操作

    什么是webpack? 他有什么优点?     首先对于很多刚接触webpack人来说,肯定会问webpack是什么?它有什么优点?我们为什么要使用它?     Webpack是前端一个工具,可以让各 ...

  3. HTML5 基础测试题

          HTML5 基础测试题 1.HTML5 之前的 HTML 版本是什么?() A.HTML 4.01 B.HTML 4 C.HTML 4.1 D.HTML 4.9 2.HTML5 的正确 d ...

  4. JS DOM 实例(5大常用实例)

    第1个实例:循环单击变色 <html lang="en"> <head> <meta charset="UTF-8"> &l ...

  5. 集合接口list与集合接口set的区别

    在Java中 除了 Map以外的集合的根接口都是Collection接口,而在Collection接口的子接口中,最重要的莫过于List和Set集合接口. 今天我们就来谈谈List集合接口与Set集合 ...

  6. [Python Test] Use pytest fixtures to reduce duplicated code across unit tests

    In this lesson, you will learn how to implement pytest fixtures. Many unit tests have the same resou ...

  7. poj 2777 Count Color(线段树、状态压缩、位运算)

    Count Color Time Limit: 1000MS   Memory Limit: 65536K Total Submissions: 38921   Accepted: 11696 Des ...

  8. nginx源代码分析--从源代码看nginx框架总结

    nginx源代码总结: 1)代码中没有特别绕特别别扭的编码实现.从变量的定义调用函数的实现封装,都非常恰当.比方从函数命名或者变量命名就能够看出来定义的大体意义,函数的基本功能,再好的架构实如今编码习 ...

  9. MySQL学习(五)——使用JDBC完成用户表CRUD的操作

    通过案例我们发现“获得连接”和“释放资源”两次代码将在之后的增删改查所有功能中都存在,开发中遇到此种情况,将采用工具类的方法进行抽取,从而达到代码的重复利用. 1.使用properties配置文件 开 ...

  10. C#生成高清缩略图 (装在自OPEN经验库)

    来源 http://www.open-open.com/lib/view/open1389943861320.html 代码如下实现图片的高清缩略图 /// <summary> /// 为 ...