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
See it run
Objects at run time: who reads, who decides, and what can change in between.
Operations
Ask, decide, act
A caller that knows the voucher's rule, or most of it.
Step 1 of 5
Day 11
The voucher was valid until day 10. The cake costs 300.
Step 1: Day 11
def phone_app(v, price, day): seen = v.uses if seen > 0: v.uses = seen - 1 return price - v.cents return price- Good for
- Throwaway scripts
- Costs
- A copy of the rule per caller
- Messages
- 3
Getter, if, setter on one object: move it in.
In the real world
The same tell, don't ask doing real jobs. Pick one and step through it.
The same evening, asked and told.
Step 1 of 4
Words
| Asking 6 sheep | Telling the dog | |
|---|---|---|
| said | 12 questions | 1 sentence |
| knowledge | ||
| decides | ||
| a pond |
Two questions for each of six sheep, against one sentence.
Step 1: Words
Common mistakes
The bugs interviewers watch for, with the fix beside each.
A check in a helper file
majorThe change can still be made without it.
Wrongif voucher_ok(v): v.uses -= 1Rightanswer = v.redeem(price, day)A command without a reason
minorThe caller must ask again to explain.
Wrongreturn FalseRightreturn refused("expired")Change before the last check
criticalA refused call costs a use.
Wrongself._uses -= 1if day > self._until: return refused("expired")Rightif day > self._until: return refused("expired")self._uses -= 1Trusting an earlier question
criticalThe state may have changed.
Wrongif v.can_redeem(): v.force_use()Rightanswer = v.redeem(price, day)The object that does everything
majorIt changes for each screen and needs a database in tests.
Wrongorder.render_html()order.send_mail()Rightpage.show(order.snapshot())outbox.add(OrderPaid(order_id))A new id for each try
criticalA repeat becomes a second wish.
Wrongfor _ in range(3): service.redeem(new_id(), code)Rightrid = new_id()for _ in range(3): service.redeem(rid, code)
Interview tips
Spot it
- Getter, if, setter
- Same object each time
- Same if in two callers
Build it
- Name the wish
- Checks, change, answer
- Pass price and day in
Make it safe
- Lock inside
- UPDATE with WHERE
- Request id on a network
Know when to ask
- Screens and reports
- Choosing between objects
- The command checks again