AlgoViz

Tell, don't ask

medium 40 min

Do not read an object's state, decide for it and write the result back.

Video lesson · Chapter 1 of 6

Make a prediction

0:00 / 4:30

Tell, don't ask

1:05Reel

More reels

One idea each, a minute or less.

Play all in Bytesized Learning

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

  1. 1988

    Bertrand Meyer's Object-Oriented Software Construction separates commands, which change state, from queries, which answer and change nothing.

  2. 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.

  3. 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.

  4. 2006

    Martin Fowler warns in GetterEradicator against the simple goal of removing every getter.

  5. 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

Six sheep and one dog

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. 1

    Ask

    voucher.uses, voucher.until: the caller takes values out.

  2. 2

    Decide

    if uses > 0 and now < until: the caller applies a rule that is not its own.

  3. 3

    Act

    voucher.uses -= 1: the caller writes the result back.

Python
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))
Two callers, one rule, two versions of it. The app forgot the date.
Edit and run it in your browser
Python
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))
The same rule as a command. There is no way to use a voucher without it.
Edit and run it in your browser

Pictures

Where the rule lives

Asking: the rule is in every caller

Voucher+ cents: int+ uses: int+ until: Date

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

Voucher- cents, uses: int- until: Date+ redeem(price, day)

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?

CodeVerdictReason
if not set.contains(x): set.add(x)Tell: set.add(x) answers whether it was newSame 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()AskThe order is not changed
if order.status == PAID: order.status = SENTTell: 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)AskComparing 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 writes v.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 then v.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

    VoucherManager with all methods, Voucher with 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, switch on 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() beside redeem()
  • 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

IdeaIts questionHow it helps
Law of DemeterWhom may I talk to?Telling removes the need to walk to the data
EncapsulationWho may touch my fields?Private fields make telling the only way
Command query separationDoes this method change anything?Names the two kinds
Command patternCan a request be an object?Queue, undo or log a tell
ObserverWho 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.

Sources