97 Things Every Programmer Should Know

(Chris Devlin) #1

(^168) 97 Things Every Programmer Should Know


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();
}
Free download pdf