State: behaviour that depends on state

  • Lesson 21 of 32
  • 10 min
  • Intermediate
  • 13 steps

An order that can end up shipped and cancelled at once because three booleans store it. You will turn it into a state machine and see when that is worth doing.

Possible combinations
4
Nonsense combinations
0
Order state
—
checkoutOrderOrder ·shippedOrder ·isGiftOrderdraftdraftpaidpaidshippedshippedcancelledcancelledOrderOrderOrderStateinterfaceOrderStateDraftDraftPaidPaidShippedShipped3 booleansOrder with booleanslet isPaid = false;let isShipped = false;let isCancelled = false;function ship() {▸if (isPaid && !isCancelled)isShipped = true;}cancel()shipped and cancelledWhat nobody checkedfunction cancel() {▸isCancelled = true;}ship(); // isShipped = truecancel(); // isCancelled = true// shipped and cancelled at onceone active at a timeOne field, four values+type Status =+| "draft"+| "paid"+| "shipped"+| "cancelled";+let status: Status = "draft";payshipcancelcancelfinalfinalTransition tableconst transitions = {draft: {pay: "paid", cancel: "cancelled" },paid: {ship: "shipped", cancel: "cancelled" },▸shipped: {},▸cancelled: {},};paystate: paidnext() (excerpt)function next(s: Status, e: Ev) {const to = transitions[s][e];if (!to)throw new Error(`cannot ${e} when ${s}`);return to;}let order: Status = "draft";▸order = next(order, "pay"); // "paid"cancel()cannot cancel when shippedAn invalid eventorder = next(order, "ship");// order === "shipped"▸next(order, "cancel");// Error: cannot cancel when shippedone active stateFinite state machinestatesa finite numberactiveone at a timeeventstrigger transitionsstate + eventalways the same targetper the Stately docsdelegatesimplementsInterface and contextinterface OrderState {pay(o: Order): void;ship(o: Order): void;}class Order {state: OrderState = new Draft();▸ship() { this.state.ship(this); }}state.ship(this)ship() → ShippedA concrete stateclass Paid implements OrderState {pay() {throw new Error("already paid");}ship(o: Order) {▸o.state = new Shipped();}}table or classes?Table or classesformtableclassessize1 object1 class per statelogic per statelittlea lotreading the flowat a glancespread outa boolean is enoughWhen not to use it2 states, no rulesa boolean is enoughrules that change oftenworkflow engine«State is a library»it is a patternstartState in one tableproblemtangled booleanssolutionstates + transitionsinvalid eventclear errorlittle logica tablea lot of logicone class per statedo not use itwith 2 states, no rules
  • request
  • response
  • event
  • failed request

Step 1 of 13

Problem

An order stored as three booleans

A shop stores each order with three fields: isPaid, isShipped and isCancelled. To ship, ship() checks that it is paid and not cancelled.

Three booleans give 2 × 2 × 2 = 8 combinations. Only 5 describe a real order; the other 3 (shipped without paying, or shipped and cancelled) should not exist, but nothing in the code prevents them.

Step 2 of 13

Problem

Cancelling an order that already left

Someone writes cancel() and only sets isCancelled = true. They forgot to check isShipped.

Now an order that already left the warehouse can be shipped and cancelled at the same time. There is no error: the impossible state is saved silently and shows up weeks later in a report.

Step 3 of 13

Concept

One field with named states

Change the question: instead of three yes/no flags, which state is the order in? Here there are four: draft, paid, shipped and cancelled.

A single status field holds one of those values, and only one at a time. «Shipped and cancelled» can no longer be written: combinations drop from 8 to 4 and impossible ones from 3 to 0.

What changed

  • type Status
  • isPaid, isShipped, isCancelled

Step 4 of 13

Concept

Which events move the order

A state is not enough: how you get there matters too. The arrows are transitions and each one has an event: pay goes from draft to paid, ship from paid to shipped, and cancel works from draft or from paid.

This is a state machine. Careful: an enum alone is not one. It becomes one when something blocks the transitions that are not in the diagram.

Step 5 of 13

Technique

Transitions written as data

The most direct form in TypeScript: an object where each state lists the events it accepts and where each one leads.

shipped and cancelled have {}: they are final states and accept no event. If it is not in the table, it cannot happen.

Step 6 of 13

Technique

`next()` applies an event

next(state, event) looks it up in the table (Ev is "pay" | "ship" | "cancel"). If it finds a target, it returns it; if not, it throws an error with a clear message.

The order starts in draft. With next(order, "pay") it moves to paid. Nobody changes the state by hand: every change goes through the table.

What changed

  • function next()

Step 7 of 13

Solution

An invalid event is rejected out loud

The order is already shipped and a cancel arrives. The table has no cancel for shipped, so next throws cannot cancel when shipped.

It is the same bug as step 2, but now it fails right away with a message that says what happened, instead of saving an impossible order.

Step 8 of 13

Technique

How a state machine library defines it

The Stately docs (the team behind XState) describe a finite state machine like this: a finite number of states, only one active at a time, events that trigger transitions, and each state-event pair always leads to the same target.

Your table follows all four rules without installing anything. State is a pattern, not a library: XState adds tools on top, but this is the idea.

Step 9 of 13

Solution

The book's form: one class per state

The GoF book's State pattern solves it with objects: an OrderState interface with one method per event (cancel works the same way) and one class per state that implements it: Draft, Paid, Shipped (and Cancelled, not drawn).

Order keeps its current state in a field and delegates every call to it: ship() does this.state.ship(this). Order has no if about its state.

What changed

  • interface OrderState

Step 10 of 13

Technique

Each state knows what to do and where to go

With the order paid, state is a Paid. Its ship() sets o.state to a Shipped; its pay() throws, because it is already paid.

Each state's rules live together in its class. If Paid has a lot of logic of its own (refunds, notices, deadlines), this form organises it better than a table.

Step 11 of 13

Trade-off

Table or classes: it depends on how much each state does

The table is short and reads at a glance: ideal when a state only decides where to go. Classes weigh more (one type per state), but win when each state has its own behaviour.

Both give you what matters: impossible states that can no longer be written and a diagram you can review. The price, either way, is modelling up front and having more types.

Step 12 of 13

Trade-off

When a state machine is overkill

With 2 states and no rules between them, a boolean is enough: isGift can go from true to false whenever you like and there are no transitions to guard.

And if the business defines the transitions and they change often (configurable approvals, steps being added), they are workflow data: a table in the database or a workflow engine fits better than classes in the code.

Step 13 of 13

Summary

Named states and explicit transitions

When behaviour depends on a state and booleans get tangled, name the states and write which events lead from one to another. Anything not allowed fails with a clear error.

Use a table if each state only decides where to go, and one class per state if each one has a lot of logic. With two states and no rules, stay with a boolean.

You will learn

  • Spot the problem: several booleans that allow impossible combinations.
  • Model a process as named states and transitions triggered by events.
  • Write a transition table that rejects invalid events.
  • Apply the book's form: one class per state and a context that delegates.
  • Choose between a table and classes, and know when a boolean is enough.