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.

时间: 2024-12-25 12:56:36

Thinking in States的相关文章

利用Saltstack的States初始化系统

今天和大家介绍一下如何运用State初始化系统吧 States是satlstack中的配置语言  安装软件包.管理配置文件都需要编写一些states sls文件   states sls使用YAML语法 查看所有states列表[[email protected]    pillar]#    salt 'onde1' sys.list_state_modules    (node1是被管理节点的ID) 查看states模块功能[[email protected]    pillar]#    

SaltStack 入门到精通 - 第八篇: 了解States

什么是Salt States Salt States是Salt模块的扩展 主系统使用的状态系统叫SLS系统. SLS代表Saltstack State. Salt状态是一些文件,其中包含有关如何配置Salt 子节点的信息. 这些状态被存在一个目录树下,可以用许多不同的格式来写. 我们可以把这些Salt States当作是对minion的管理脚本的配置模式,通过配置sls文件,指定目标minions,可以实现在master上对minions的运行状态进行管理. Salt State树 跟系统文件树

STATES TUTORIAL(第四部分)

MOD AGGREGATE STATE RUNTIME MODIFICATIONS 略 ALTERING STATES 略 FILE STATE BACKUPS 可以在多个地方设置minion端的文件备份.示例: backup_mode: minion 或 1 /etc/ssh/sshd_config: 2 file.managed: 3 - source: salt://ssh/sshd_config 4 - backup: minion BACKED-UP FILES 备份文件的位置位于mi

Entity Framework学习(一) - Entity Framework Add and Attach and Entity States

Entity Framework Add and Attach and Entity States Entity Framewokr 新增.附加.实体状态 This topic will cover how to add and attach entities to a context and how Entity Framework processes these during SaveChanges. Entity Framework takes care of tracking the s

翻译经典之《Cisco Lan Switching》第六章(六):Five STP States

[版权声明:原创翻译文章,翻译水平有限,错误在所难免,翻译作者对文章中存在的错误或遗漏所造成后果不承担任何责任,请谨慎转载.转载请保留本声明及出处:blog.csdn.net/shallnet ,下载该书英文版] 在网桥将其端口角色按根端口.指定端口.非指定端口分类之后,创建无环的拓扑就简单明了了:根端口和指定端口转发数据流量,非指定端口阻塞数据流量.虽然在一个稳定的网络中转发和阻塞是仅有的两种使用到的状态,但表6-3列出了STP实际上的五中状态. Table 6-3. STP States S

自动化运维Saltstack系列(四)之States配置管理和jinja模板的使用

States配置管理 States是Saltstack中的配置语言,在日常进行配置管理时需要编写大量的States SLS文件,而编写这些SLS文件的一般步骤也就是我们平时手动配置一台服务器的步骤:首先安装源码包,然后管理一个配置文件,最后再保证这个服务的开机启动及正常运行.其中使用到的states模块功能需要我们一边学习一边实践加强理解. 接下来,我们通过一个简单的例子来理解Saltstack配置管理的基本原理--安装keepalived 1)修改master配置文件的file_roots根目

Git Tutorial 7 - File States

File States Overview Every file in your working directory is mainly in one of 2 states: 1. Tracked : All files that were committed to the last snapshot in Git repository are in state Tracked. They can be one of the following states: 1.1 Unmodified : 

暴搜 - Codeforces Round #327 (Div. 2) E. Three States

E. Three States Problem's Link Mean: 在一个N*M的方格内,有五种字符:'1','2','3','.','#'. 现在要你在'.'的地方修路,使得至少存在一个块'1','2'和'3'是连通的. 问:最少需要修多少个'.'的路. analyse: 想法题,想到了就很简单. 直接暴力枚举每个国家到每个可达的点的最小代价,然后计算总和取最小值. dis[k][x][y]表示第k个国家到达坐标(x,y)的点的最小代价. Time complexity: O(N) vi

render states

Direct3D is basically a state machine 不会改变直到我们改变 以下是渲染的设置 1. ID3D11RasterizerState: This interface represents a state group used to configure the rasterization stage of the pipeline.2. ID3D11BlendState: This interface represents a state group used to

[AngularJS] Consistency between ui-router states and Angular directives

ui-router's states and AngularJS directives have much in common. Let's explores the similarities between the two and how these patterns have emerged in Angular. Keeping your states and directives consistent can also help with refactoring as your app