CodePark/ questions / OOP principles & composition
START PRACTICINGPRACTICE
Backend question · Software design & patterns › OOP principles & composition

Which change best applies the "Tell, Don't Ask" principle to this code?

if (account.getBalance() >= amount && !account.isFrozen()) {
  account.setBalance(account.getBalance() - amount);
} else {
  throw new Error("Cannot withdraw");
}
Move the logic into account.withdraw(amount), which checks its own rules and updates its own balance

The right answer is to move the logic into account.withdraw(amount). Tell, Don't Ask means you tell an object what to do, and it uses its own data. You do not pull its data out and decide for it.

"Move the check into a static helper
AccountUtils.canWithdraw(account, amount)" is tempting but wrong. The helper still asks the object for its data. The rule still lives outside the object, so other callers can skip it.