Video in progress
Show the "Tell, don't ask" principle with a code example.
Instead of asking an object for its state and making the decision outside, you tell the object what to do, and it makes the decision itself. That way the rule sits next to the data.
📖 Answer
The "ask" style:
if (account.getBalance().compareTo(amount) >= 0 && !account.isBlocked()) {
account.setBalance(account.getBalance().subtract(amount));
} else {
throw new InsufficientFundsException();
}
The problems:
- the rule ("you can't withdraw from a blocked account") is outside and may be forgotten somewhere else;
setBalanceis exposed, so anyone can change the balance however they like;- two threads can check at the same time and both withdraw, because the check and the change are separate.
The "tell" style:
account.withdraw(amount);
public void withdraw(Money amount) {
if (blocked) throw new AccountBlockedException(id);
if (balance.lessThan(amount)) throw new InsufficientFundsException(id);
balance = balance.minus(amount);
}
Now Account guards its own rules.
It has limits too: asking for data for display (UI, a report) is fine, and there is nothing wrong with an account.balance() getter. The principle is about making decisions: if you are changing the object's own state based on the result of a getter, that logic should move inside the object.
Sign up to mark studied questions and save your progress.