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

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

appPhoneAppseennothingpaid?CAKEVouchercents500uses1untilday 10

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 sheepTelling the dog
said12 questions1 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

    major

    The change can still be made without it.

    Wrong
    if voucher_ok(v):    v.uses -= 1
    Right
    answer = v.redeem(price, day)
  • A command without a reason

    minor

    The caller must ask again to explain.

    Wrong
    return False
    Right
    return refused("expired")
  • Change before the last check

    critical

    A refused call costs a use.

    Wrong
    self._uses -= 1if day > self._until:    return refused("expired")
    Right
    if day > self._until:    return refused("expired")self._uses -= 1
  • Trusting an earlier question

    critical

    The state may have changed.

    Wrong
    if v.can_redeem():    v.force_use()
    Right
    answer = v.redeem(price, day)
  • The object that does everything

    major

    It changes for each screen and needs a database in tests.

    Wrong
    order.render_html()order.send_mail()
    Right
    page.show(order.snapshot())outbox.add(OrderPaid(order_id))
  • A new id for each try

    critical

    A repeat becomes a second wish.

    Wrong
    for _ in range(3):    service.redeem(new_id(), code)
    Right
    rid = 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