Chapter 84. Thinking in States

Niclas Nilsson

image with no caption

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 converting 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 trying 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. ...

Get 97 Things Every Programmer Should Know now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.