AlgoViz

State pattern

medium 55 min

The State pattern lets an object change its behaviour when its internal state changes.

Video lesson · Chapter 1 of 6

Make a prediction

0:00 / 4:37

See it run

Objects at run time: who holds which state, and who answers the same call.

Operations

Vending machine

Buy a cola for 150 with 200 and 100. The arrow from the machine is its current state.

Step 1 of 10

Ready

stateashaCustomermachineVendingMachinebalance0chosennonecoin tray0cola5noCoinNoCoinhasCoinHasCoinsoldSold

Display: INSERT COIN

The machine holds noCoin. Display: INSERT COIN.

Step 1: Ready

class VendingMachine:    def select_product(self, code):        self._state.select_product(self, code)class NoCoin:    def insert_coin(self, m, cents):        m.balance = cents        m.go(m.has_coin, "SELECT PRODUCT")    def select_product(self, m, code):        m.display = "INSERT COIN FIRST"class HasCoin:    def insert_coin(self, m, cents):        m.balance += cents    def select_product(self, m, code):        if m.balance >= m.slots[code].price:            m.chosen = code            m.go(m.sold, "DISPENSING")class Sold:    def insert_coin(self, m, cents):        m.give_back(cents)    def dispense(self, m):        m.give_back(m.balance - m.slots[m.chosen].price)        m.balance, m.chosen = 0, None        m.go(m.no_coin, "INSERT COIN")
Watch
The state arrow
Result
Same call, other answer

Follow the arrow from the machine. It moves three times.

In the real world

The same state pattern doing real jobs. Pick one and step through it.

The answer of the first call was lost, so the shop calls again.

Step 1 of 5

Accepted

IdEventStateAnswer
1e1payNew to PaidPaid
2
3
4
5

Event e1, pay. The order moves from New to Paid, and the answer is stored with the id.

Step 1: Accepted

Common mistakes

The bugs interviewers watch for, with the fix beside each.

  • Taking the money before delegating

    critical

    In Sold the coin is refused, but it is already in the balance.

    Wrong
    def insert_coin(self, cents):    self.balance += cents    self._state.insert_coin(self)
    Right
    def insert_coin(self, cents):    self._state.insert_coin(self, cents)
  • A public setter for the state

    critical

    Anyone can jump to Sold without paying, and hooks and log are skipped.

    Wrong
    machine.state = machine.sold
    Right
    def go(self, state):        # tools for states only    log(self._state, state)    self._state = state
  • Conditions about the state in the context

    major

    The question you removed is back.

    Wrong
    def cancel(self):    if self._state is self.has_coin:        self.give_back(self.balance)
    Right
    def cancel(self):    self._state.cancel(self)
  • Data in a shared state object

    critical

    All documents share the object, so they share the reviewer.

    Wrong
    class Review:    def __init__(self):        self.reviewer = None
    Right
    class Document:    def __init__(self):        self.reviewer = None
  • Waiting inside a transition

    major

    Nobody can press anything for ten seconds, and a lock is held.

    Wrong
    def dispense(self, m):    sleep(10)    m.go(m.no_coin)
    Right
    def enter(self, m):    m.motor.start()         # the sensor sends dispense
  • Forgetting a cell silently

    major

    An empty inherited method swallows the event.

    Wrong
    class MachineState:    def insert_coin(self, m, cents): pass
    Right
    class MachineState(ABC):    @abstractmethod    def insert_coin(self, m, cents): ...

Interview tips

  • Draw first

    • Events are verbs.
    • States are adjectives.
    • Fill every cell.
  • Keep the context boring

    • One line per event.
    • Data that outlives states.
    • One writer of the state.
  • Refuse completely

    • Return the coin.
    • Say why.
    • Stay in the state.
  • Know the neighbours

    • Strategy is chosen.
    • State moves on.
    • A table is smaller.
  • In production

    • One event at a time.
    • Name, data, version.
    • Ids for events.