Tell, Don't Ask
Tell, Don’t Ask is a design guideline: instead of pulling data out of an object with getters and then deciding what to do with it from the outside, tell the object what you want done and let it decide how, using the data it already holds.
// Ask
if (invoice.getBalance() > 0) {
invoice.setStatus("overdue")
}
// Tell
invoice.markOverdueIfUnpaid()
The “Ask” version leaks the invoice’s internal rule – what counts as overdue – into the caller. The “Tell” version keeps that rule where the data lives.
- It’s close kin to the Law of Demeter: asking for state and then chaining further calls on it is exactly the kind of reach-through-a-stranger the Law of Demeter warns about.
- Following it tends to raise cohesion, since behavior moves next to the data it operates on rather than staying scattered across callers.
- See coupling's recommended reading for a source that discusses this alongside coupling more generally.