Part 5 of 7 · 1 min read
Tell, do not ask
Put the behaviour next to the data.
A common design smell (common practice, not from the books) is code that asks an object for its data, makes a decision, and then changes the object. For example:
// asking
if (account.balance() >= amount) {
account.setBalance(account.balance() - amount);
}
This spreads the rule over every caller and invites a race when two callers run at once. The better design is to tell the object what to do: account.withdraw(amount). The rule lives in one place, with the data it guards. Level 2 returns to this idea under the Law of Demeter.
Check yourself: 1. What is wrong with the asking version? 2. Where does the rule live in the telling version? 3. Which concurrency risk does asking add?