Skip to the page

Design patterns · mid

State pattern or transition table

A lifecycle such as an order or a vending machine is a state machine. Use a transition table when the main rule is which move is allowed, and the State pattern when behaviour differs a lot in each state.

The notes

What you must know

  • A switch is fine for 2 or 3 states used in one place. Repeated in every method it drifts and bugs hide.
  • Transition table: an enum of states and a map of allowed next states (or allowed events per state). One transition(event) method checks it. It is easy to read, test and draw.
  • State pattern: one class per state, best when behaviour differs a lot per state. A vending machine insertCoin does different things in each state. It costs more classes.
  • Mix both: a table for allowed transitions, plus hooks or listeners for actions on entering a state.
  • Store the status as an enum column with a version. Update with compare-and-set: WHERE status = ? AND version = ?.
  • Duplicate events are idempotent: the same transition again is a no-op. Cancel is allowed only from early states.
  • Adding an on-hold state is one enum value and a few table rows in the table design.

The red pen

Common traps: mistake → fix

  • Mistake: Always use the State pattern for a lifecycle

    Fix: five states with no per-state behaviour become ten classes of two lines.

  • Mistake: Status can be a free string

    Fix: any code can set a wrong value.

  • Mistake: Two threads can change the status safely with a plain set

    Fix: use compare-and-set so cancel and accept cannot both win.

Easy to hard

Questions interviewers ask, easy to hard

  1. How do you model an order status?
  2. Switch, transition table or State pattern: how do you choose?
  3. How do you handle two events at the same time?
  4. Add an on-hold state. What changes?

Your first interview is free

Sign up and start with a 15-minute interview with the full report, and an English conversation. No card needed.

Start your free interview