Chapter 84. Thinking in States

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. You may still want isComplete for clarity ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access