Tell, don't ask
medium 40 minDo not read an object's state, decide for it and write the result back.
Video lesson · Chapter 1 of 6
Make a prediction
Tell, don't ask
1:05Reel
More reels
One idea each, a minute or less.
Law of Demeter or tell, don't ask?
0:31Reel
Theory
Read or listen first. About 2 min.
What it is
Tell, don't ask is advice about where a decision lives. Asking: the caller reads values from an object, decides what they mean, and changes the object. Telling: the caller names the wish, and the object reads its own values, decides and changes itself.
The difference is not the word get. A method is_valid() is a question, and it may be a good one. The trouble starts when the caller uses the answer to make a decision for the object and then acts on it.
Telling does not mean silence. The object answers with a result: done, or refused and why. The answer is about what happened, not raw material for the caller's next if.
Why it exists
A rule that lives in callers lives in many places. A shop has a web page, an app and a phone desk. If each checks a voucher itself, three copies of the rule drift apart, and the fourth caller forgets one line.
Between the question and the action the world can change. Two callers ask whether a voucher is unused, both hear yes, and both use it. When the check and the change are one call, there is one place to make it safe.
It keeps data and behaviour together, which is what objects are for. Data that everyone reads and writes cannot change its form. Data behind a command can.
A short history
1988
Bertrand Meyer's Object-Oriented Software Construction separates commands, which change state, from queries, which answer and change nothing.
1997
Alec Sharp's Smalltalk by Example contrasts the two styles: procedural code gets information and then decides, object code tells objects to do things.
2003
Andy Hunt and Dave Thomas use the name in IEEE Software, January/February: a paperboy should not ask for the wallet but tell the customer to pay.
2006
Martin Fowler warns in GetterEradicator against the simple goal of removing every getter.
2013
Fowler's note TellDontAsk calls it a useful reminder to keep behaviour with its data, and says they do not follow it as a fixed rule.
Words to know
- Command
- A call that asks an object to do something. It may change state.
- Query
- A call that answers a question and changes nothing that others can see.
- Command query separation
- Each method is one of the two. Asking a question should not change the answer.
- Check then act
- Test a condition, then act on it later. The condition may be false by then.
- Anemic object
- A class with only fields and accessors. Its rules live in other classes.
- Feature envy
- A method that uses another object's data more than its own.
- Invariant
- A statement about an object that must always be true, such as uses left is never negative.
- Result object
- A value that says whether a command worked and, if not, why.
The solution, twice
Reach the regular design first. Then go where a FAANG interviewer digs.
Understand it
Start here
Bring them in
The shepherd knows what should happen. The dog knows how.
The shape
Ask, decide, act
The smell has three beats, and all three are about the same object.
- 1
Ask
voucher.uses,voucher.until: the caller takes values out. - 2
Decide
if uses > 0 and now < until: the caller applies a rule that is not its own. - 3
Act
voucher.uses -= 1: the caller writes the result back.
class Voucher: # only data def __init__(self, cents, uses, until): self.cents, self.uses, self.until = cents, uses, untildef web_page(v, price, day): if v.uses > 0 and day <= v.until: v.uses -= 1 return max(0, price - v.cents) return pricedef phone_app(v, price, day): if v.uses > 0: # no date check v.uses -= 1 return price - v.cents # can be negative return pricev = Voucher(500, 2, until=10)print("web, day 11:", web_page(v, 300, 11))print("app, day 11:", phone_app(v, 300, 11))class Voucher: def __init__(self, cents, uses, until): self._cents, self._uses, self._until = cents, uses, until def redeem(self, price, day): """The new price. A refused voucher changes nothing.""" if self._uses == 0 or day > self._until: return price self._uses -= 1 return max(0, price - self._cents)v = Voucher(500, 2, until=10)print("web, day 11:", v.redeem(300, 11))print("app, day 11:", v.redeem(300, 11))print("app, day 9:", v.redeem(300, 9))Pictures
Where the rule lives
Asking: the rule is in every caller
1/3Data without behaviour
The voucher has three public fields and no method. Somebody else must know what they mean.
depends on
Telling: one rule, next to its data
1/3The rule moves in
Fields become private. One command is public.
usesdepends on
Asking: four messages and a gap
Telling: one message
Which is it?
Good questions and bad questions
May I ask?
| Code | Verdict | Reason |
|---|---|---|
if not set.contains(x): set.add(x) | Tell: set.add(x) answers whether it was new | Same object, ask then act |
if lamp.is_on: lamp.off() else: lamp.on() | Tell: lamp.toggle() | The lamp knows its state |
label.text = order.total() | Ask | The order is not changed |
if order.status == PAID: order.status = SENT | Tell: order.ship() | A transition is a rule of the order. See State |
if shape.kind == 'circle': ... | Tell: shape.draw(canvas) | Asking for the type is the same smell. See open/closed |
cheapest = min(offers, key=price) | Ask | Comparing several is the caller's decision |
Three callers check a voucher before they use it. What do you do?
BreaksShare a helper function
- How
voucher_ok(v)in a utils file, then each caller writesv.uses -= 1.- Limit
- One check, but the change can still be made without it, and there is a gap between both.
- Choose when
- Never as the end point.
WorksA query on the voucher
- How
v.is_usable(day)and thenv.use().- Limit
- The rule has a home. Callers can still forget the question or ask too early.
- Choose when
- To grey out a button, next to a command that checks again.
StrongOne command with a result
- How
v.redeem(price, day)checks, changes and answers.- Limit
- Needs a thought about the answer: exception, value or event.
- Choose when
- Whenever state changes.
Find it
Signals in your own code
Getter, if, setter
Three lines on one object. The classic.
Manager and data
VoucherManagerwith all methods,Voucherwith all fields. They are one class.The same if twice
Two callers test the same fields of the same object.
Questions about type
isinstance,kind,switchon somebody else's enum.Setters in a fixed order
Callers must set the date before the status. Only the object should know.
Comments that beg
Remember to check X before calling Y.
Too far
When it is taken too literally
Reasonable
- Queries that change nothing
- A frozen snapshot for screens and reports
can_redeem()besideredeem()- Reading two objects to decide which one to tell
Overdone
order.render_html(),order.save_to_sql(),order.send_mail()- Banning every getter
- Callbacks for each field only to avoid a return value
- One object that decides for its neighbours
The first bad line matters most. Telling moves decisions about the data into the object. How a page looks is not such a decision. If every feature becomes a method of the order, the order has many reasons to change: see single responsibility and separation of concerns.
Neighbours
Related ideas
| Idea | Its question | How it helps |
|---|---|---|
| Law of Demeter | Whom may I talk to? | Telling removes the need to walk to the data |
| Encapsulation | Who may touch my fields? | Private fields make telling the only way |
| Command query separation | Does this method change anything? | Names the two kinds |
| Command pattern | Can a request be an object? | Queue, undo or log a tell |
| Observer | Who wants to know? | Objects announce changes, so others need not ask again and again |
Summary
The whole topic in one minute.
Find code that reads an object, decides, and writes back to the same object. Move the whole decision into one method of that object, and let it return a result.
Questions stay welcome when they have no later action on the same object: screens, reports, decisions that belong to the caller or need several objects.
Over threads, databases and networks the idea becomes a necessity: one atomic command instead of a read and a write, sent with an id so that it can be repeated.
- Ask, decide, act on the same object is the smell.
- Move the decision to the data and give it the name of the wish.
- A command may answer: done, or refused and why.
- Questions without a later change are fine.
- One command is also the only place where a race can be closed.
- Do not move screens and storage into the object.