Thinking in States
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的更多相关文章
- Life Cycle of Thread – Understanding Thread States in Java
Life Cycle of Thread – Understanding Thread States in Java 深入理解java线程生命周期. Understanding Life Cycle ...
- Hover States - 有趣的用户界面及交互设计
Hover States 一组新潮的和有趣的用户界面和交互设计的集合.Hover States 的目标是要成为设计师和开发人员灵感来源,向人们展示目前人们正在做的各种网站中令人惊奇的效果.他们认为交互 ...
- Channel States
Introduction A channel (a call) will go through many different states during its lifetime. Here we w ...
- flex4的s:states和mx:states的区别
http://help.adobe.com/en_US/Flex/4.0/UsingSDK/WS2db454920e96a9e51e63e3d11c0bf63611-7ffa.html#WS43468 ...
- 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 ...
- PROCESS STATES
COMPUTER ORGANIZATION AND ARCHITECTURE DESIGNING FOR PERFORMANCE NINTH EDITION To understand the ope ...
- [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 ...
- codeforces 590C C. Three States(bfs+连通块之间的最短距离)
题目链接: C. Three States time limit per test 5 seconds memory limit per test 512 megabytes input standa ...
- Codeforces Round #327 (Div. 2) E. Three States
题目链接: 题目 E. Three States time limit per test:5 seconds memory limit per test:512 megabytes 问题描述 The ...
- I.MX6 show battery states in commandLine
#/bin/sh # I.MX6 show battery states in commandLine # 声明: # 在命令行下自动显示电池状态的信息. # # -- # set battery r ...
随机推荐
- 小试牛刀之sort()排序的实现
受大学室友的鼓动,我也打算利用公众平台来记录自己的前端知识积累,同时呢,自己总结的东西,总归会有局限性,希望小伙伴能给我指点迷津.知识就是一张巨大的网,作为一名摸不清头绪的入学者,唯一能做的事情就是吐 ...
- Svn 提交新文件
1.右击文件: 2.按图做:
- 《你又怎么了我错了行了吧团队》第七次作业:团队项目完善&编码
<你又怎么了我错了行了吧团队>第七次作业:团队项目完善&编码 项目 内容 这个作业属于哪个课程 软件工程 这个作业的要求在哪里 实验十一 团队名称 你又怎么了我错了行了吧 作业学习 ...
- 前端和后台对接时对sign加密方法
前端和后台对接时对sign加密方法 /*后台php对接进行sign标签加密 1 获取向后台请求的数据data(key/value方式),可以是个对象(obj),也可以是数组(arr); 2 将数据的k ...
- inputstream输出为String
import java.io.IOException; import java.io.InputStream; import org.apache.http.HttpEntity; import or ...
- m_Orchestrate learning system---一、amazeui如何使用
m_Orchestrate learning system---一.amazeui如何使用 一.总结 一句话总结:先花几分钟把所有功能稍微看一下,然后做的时候就会特别快,所以,多学习,学得越多做的越快 ...
- 如何比较Keras, TensorLayer, TFLearn ?——如果只是想玩玩深度学习,想快速上手 -- Keras 如果工作中需要解决内部问题,想快速见效果 -- TFLearn 或者 Tensorlayer 如果正式发布的产品和业务,自己设计网络模型,需要持续开发和维护 -- Tensorlayer
转自:https://www.zhihu.com/question/50030898/answer/235137938 如何比较Keras, TensorLayer, TFLearn ? 这三个库主要 ...
- chrome的全局搜索快捷键
常用 文件内搜索 ctrl+f 使用快捷键 ctrl+shift+f, 就会进入到全局搜索模式 打开文件:ctrl+o 打开DevTools 你可以通过以下任何一种方式来访问DevTools: 打开浏 ...
- jQuery学习(七)——使用JQ完成下拉列表左右选择
1.需求:实现以下功能 2.步骤分析: 第一步:确定事件(鼠标单击事件click) 第二步:获取左侧下拉列表被选中的option($(“#left option:selected”)) [假设左侧se ...
- 【原创】如何使用一句SQL计算工作日天数?
现在有这样一个需求,要求计算两个日期间的工作日天数,要求除去节假日,其中节假日有一张配置表,具体的格式如下: 开始日期 结束日期 节假日类型 节假日名称 2013-08-10 2013-08-12 ...