Thinking in States

翻译 2015年07月11日 07:24:14

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

People in the real world have a weird relationship with state. This morning I stopped by the local s...

读thinking in java的收获(三)--用eclipse输入main中args运行参数

温故而知新,当站到一个高度的时候发现最开始遇到的困难其实并没有那么麻烦,在现有的基础上多拓展一点会有不同的发现哟。 在做本书第二章练习第10题的时候,编写一个程序从命令行获取三个参数, 代码如下: p...

《大象--Thinking in UML 第二版》已于近日在当当首发,同时邀请各位加入新浪微博[大象-thinkinginUml群]:http://q.weibo.com/1483929

《大象--Thinking in UML 第二版》已于近日在当当首发,感兴趣的朋友可以去看看http://product.dangdang.com/product.aspx?product_id=22...

00 我读Thinking in java(第四版)

00 我读Thinking in java(第四版)

Thinking in Java--java正则表达式初步学习

正则表达式是一种强大的文本处理工具,使用正则表达式我们可以以编程的方法,构造复杂的文本模式,并且对输入的字符串进行搜索.在我看来,所谓正则表达式就是我们自己定义一些规则,然后就可以验证输入的字符串是不...
  • acm_lkl
  • acm_lkl
  • 2015年06月12日 16:21
  • 768

Thinking in java(11章 对象的集合)

第十一章:对象的集合 11.1  数组 数组与其他种类的容器之间的区别:效率、类型和保存基本类型的能力。在Java中,数组是一种效率最高的存储和随机访问对象引用序列的方式。它是简单的线性序列,但是因其...

《Thinking In Algorithm》09.彻底理解递归

递归真的非常非常重要!!! 我们直接从例子开始吧! 一:简单实例 1.阶乘的实现 写个函数实现   N! = N × (N-1) × (N-2) × ... × 2 × 1 publ...
  • SpeedMe
  • SpeedMe
  • 2014年03月20日 23:20
  • 9423

java Semaphore信号亮-允许多个任务同时访问这个资源--thinking in java21.7.6

java Semaphore信号亮-允许多个任务同时访问这个资源--thinking in java21.7.6

从头认识Java之(Thinking in Java随记系列)Ⅰ

今天正式毕业了,在北京的某公司也顺利结束了实习。从学校回北京后直接转正了,虽然今天周六还是去公司转悠转悠,一直想好好看看《Thinking in Java》(第四版),毕业了,全身心投入到工作中,自然...
内容举报
返回顶部
收藏助手
不良信息举报
您举报文章:Thinking in States
举报原因:
原因补充:

(最多只允许输入30个字)