Pattern 12/22 · Behavioral

State

Package each state of an object as its own set of behaviour, so the state itself decides which actions are valid and which state it moves to next — instead of making every other place guess from `status` with if/else.

Behavioral●●○14 min read8 stepsalso known as: State Machine, FSM, States
state machineif elsestatetransitionbehavioraltypescript

01 — It starts with code that is breaking

Problem

Your shop has an Order class with a status field. The business starts out simple: the customer places an order and it's pending, payment goes through and it's paid, the warehouse sends it and it's shipped. You write pay(), ship(), cancel() — each one starts with a few lines checking status, then does its job. Everything works.

Next quarter brings refunded, failed, partially_refunded, and two new rules: COD orders can ship before they're paid, and refunded orders must not ship. Every new rule means opening every method on Order, because each method remembers its own fragment of the rules. ship() misses one refund check and goods leave the warehouse for an order the customer already got their money back on.

Then status leaks out of the class. The order detail page has if (order.status === "paid") to show the "Ship" button. The API guard has a check saying the same thing. The reporting cron has a third switch. The same fact — "paid may go to shipped" — is written in three places, and one of them lives in another team's repo.

The characteristic bug in code like this isn't "wrong formula", it's an invalid transition slipping through. Two cancel webhooks arrive at the same time, both see status === "paid", both pass the check, and the order gets refunded twice. Nothing defines "from this state you may only go to those states", so every caller is responsible for remembering — and everyone forgets something.

In short: the object's behaviour depends on the status data, but the rule of "which status may do what, and go where" isn't centralised anywhere. A state machine turns that invisible, scattered rule into something tangible: readable on one screen, able to block bad transitions, and testable with a single loop.

02 — The idea, before touching code

Solution

Each state is its own unit of code, holding the behaviour that applies in that state plus the list of valid next states. Order becomes just a shell: it holds the current state, receives commands, hands them to the current state, then switches state if the state allows it. No other module in the system is allowed to ask "what's the status" and decide for itself anymore.

In TypeScript, what you usually need is not "one class per state" but a transition table: Record<From, To[]>, plus guards if needed. That table is the machine — readable in 10 seconds, serialisable to JSON so the UI can render buttons, and every state change goes through exactly one function. A bad transition dies right at that boundary and never reaches business logic. The GoF version (one class per state) is only worth it when each state has a lot of its own behaviour, not just "where it's allowed to go".

Don't confuse it with Strategy: the code structure of these two patterns is nearly identical — one object delegating to another. The intents are opposite. Strategy is the client choosing an algorithm ("today we calculate fees this way"); State is the state itself deciding, and transitioning itself ("while paid, ship() is valid and submit() isn't"). If you write State and the client still calls order.setState(x) from outside, you've written Strategy under another name.

03 — Doing it for real, one code fragment per step

Step by step

1

Draw the machine first: the set of states and the set of transitions

Before writing code, list two things: the finite set of states and the set of valid transitions (from → to, with conditions). If you can't list these two, you don't understand the business yet — don't rush into writing classes.

Write that table to a file, keep it next to the code, and review it with the business people, not just the compiler. This is the pattern's real deliverable; the code is only a translation of the table.

textorder-machine.txt
STATE      ACTION     NEXT        WHO CALLS IT
draft      submit     pending     customer clicks "Place order"
draft      cancel     cancelled   customer cancels before paying
pending    pay        paid        webhook from payment gateway
pending    expire     cancelled   cron: payment window expired
paid       ship       shipped     warehouse staff
paid       refund     cancelled   customer support
shipped    (no transitions)   <- final state
cancelled  (no transitions)   <- final state
These eight lines are the entire order business. The "double refund" bug isn't in the table, so it can't run.
Key pointMachine = set of states + set of transitions. If you can't write those two down, there's nothing to refactor yet.
2

Write the smelly version, to see where it breaks

Everyone has written this code, and it isn't wrong today. It goes wrong around the third release, when the number of rules exceeds what one person can keep in their head while reading each method.

tsorder-v1.ts
type Status = 'draft' | 'pending' | 'paid' | 'shipped' | 'cancelled'

class Order {
  status: Status = 'draft'
  refunded = false

  pay(): void {
    if (this.status !== 'pending') throw new Error('cannot pay')
    this.status = 'paid'
  }

  ship(): void {
    if (this.status !== 'paid') throw new Error('cannot ship')
    this.status = 'shipped'   // BUG: has no idea a refund might be in progress
  }

  cancel(): void {
    if (this.status === 'shipped') throw new Error('already shipped')
    this.refunded = true
    this.status = 'cancelled'
  }
}
Each method remembers its own rules. The combination paid → refund in progress → ship never crossed anyone's mind while writing them.
Key pointThe smell isn't the if. The smell is scattered transition rules: each method holds a fragment and none of them sees the whole picture.
3

Define the contract for a state

Every state is an object with the same shape. It receives the context object and answers for itself: is this action valid, and what's the next state.

The ? carries the message: if the state doesn't have that method, the action doesn't exist in this state. You no longer need to write if (status === ...) throw.

tsorder-state.ts
import type { Order } from './order'

export type Status = 'draft' | 'pending' | 'paid' | 'shipped' | 'cancelled'
export type Action = 'submit' | 'pay' | 'ship' | 'refund' | 'cancel' | 'expire'

/** The contract: a state declares which actions it accepts, and where each one leads. */
export interface OrderState {
  readonly name: Status
  submit?(o: Order): OrderState
  pay?(o: Order): OrderState
  ship?(o: Order): OrderState
  refund?(o: Order): OrderState
  cancel?(o: Order): OrderState
  expire?(o: Order): OrderState
}
This interface stays put while every business rule changes. It describes "the shape of the question", not the answer.
Key pointThe right question is no longer "is the status paid" but "does the current state have a ship() method".
4

Each state holds its own behaviour and transitions

The whole machine fits on one screen, and every line belongs to exactly one state. A new rule ("COD can ship before pay") is one method added to pending, not a patch scattered across four files.

tsstates.ts
import type { OrderState } from './order-state'

export const draft: OrderState = {
  name: 'draft',
  submit: () => pending,
  cancel: () => cancelled,
}

export const pending: OrderState = {
  name: 'pending',
  pay: () => paid,
  expire: () => cancelled,
}

export const paid: OrderState = {
  name: 'paid',
  ship: () => shipped,
  refund: () => cancelled,
}

export const shipped: OrderState = { name: 'shipped' }     // final state
export const cancelled: OrderState = { name: 'cancelled' } // final state
A state doesn't call other states — it only returns the next state. Who swaps the state pointer is the Context's business (next step).
Key pointNew state = new object. New transition = one more line in exactly one object. Open/Closed, literally.
5

The Context only delegates, it never guesses

Order now knows nothing about transition rules. It knows exactly one thing: ask the current state, and if the state refuses, report an error with context ("it's paid, so it can't submit") instead of crashing somewhere meaningless.

For the machine to mean anything, every action has to go through apply(). If some place assigns order.state = ... directly, that machine is just decoration.

tsorder.ts
import type { Action, OrderState } from './order-state'
import { draft } from './states'

export class Order {
  private state: OrderState = draft

  constructor(readonly id: string) {}

  private apply(action: Action): void {
    const run = this.state[action] as ((o: Order) => OrderState) | undefined
    const next = run?.(this)
    if (!next) {
      throw new Error(this.id + ': cannot ' + action + ' while "' + this.state.name + '"')
    }
    console.log(this.id + ': ' + this.state.name + ' -> ' + next.name)
    this.state = next
  }

  submit() { this.apply('submit') }
  pay() { this.apply('pay') }
  ship() { this.apply('ship') }
  refund() { this.apply('refund') }
}
No branch in the Context holds business rules anymore. Adding a new action: add a one-line delegating method.
Key pointIf any module still has to read status to make a decision, your machine isn't done.
6

The pragmatic version: a transition table, no class-per-state

The truth few people mention: most states in an app have no behaviour of their own, they just block certain actions. For those, a dedicated class is pointless ceremony. A transition table expresses the same machine as data: you can log it, return it to the client, test it with one loop, and a PM can read it without knowing TypeScript.

The two versions don't conflict. Start with the table; when one state starts holding complex logic (recalculating stock, calling a refund API), promote just that state to an object. It's still one machine.

tstable-machine.ts
type S = 'draft' | 'pending' | 'paid' | 'shipped' | 'cancelled'

/** from -> list of valid to's. Anything outside this list is a BUG, not "a case we haven't written yet". */
export const NEXT: Record<S, S[]> = {
  draft: ['pending', 'cancelled'],
  pending: ['paid', 'cancelled'],
  paid: ['shipped', 'cancelled'],
  shipped: [],
  cancelled: [],
}

export function go(from: S, to: S): S {
  if (!NEXT[from].includes(to)) throw new Error(from + ' -> ' + to + ' is not valid')
  return to
}

// Testing the whole machine = 6 lines:
// for (const [from, tos] of Object.entries(NEXT))
//   for (const to of tos) expect(() => go(from as S, to)).not.toThrow()
Key pointState (GoF) and a transition table are the same machine; they differ in where behaviour lives: in classes on one side, in data on the other. Choose data until the behaviour gets thick.
7

Block bad transitions at exactly one boundary

The biggest value of a machine isn't tidier code, it's that a bad transition can't reach business logic. The precondition: every path that changes state goes through one single function — API routes, cron, migration scripts, tests. A detour around that function is a hole, not an optimisation.

A state machine also gives you idempotency almost for free. The payment webhook fires twice: the second time is paid → paid, which isn't in the table, so it's blocked at the door. No distributed lock needed for this case, and your logs shout about it instead of silently charging twice.

tsmachine.ts
export class Machine<S extends string> {
  constructor(private state: S, private next: Record<S, S[]>) {}

  get current(): S {
    return this.state
  }

  /** An error thrown here is a GOOD SIGN: it stops the bug at the boundary instead of letting it run on. */
  to(to: S): void {
    if (!this.next[this.state].includes(to)) {
      throw new Error(this.state + ' -> ' + to + ' blocked')
    }
    this.state = to
  }

  /** Lets UI/API ask "where can I go from here?" — smooth, no throwing. */
  can(to: S): boolean {
    return this.next[this.state].includes(to)
  }
}
Key pointIf bad transitions are only blocked in the UI, you don't have a machine — you have a suggestion.
8

Let the UI and API read the machine, don't make them remember

The machine is only really done when nobody guesses the state on their own anymore. The order detail page doesn't write if (status === "paid"); it asks the machine "which actions are valid from this state" and renders buttons from that list. The business changes, the buttons follow, and nobody has to edit the template.

The same list serves the API guard: a ship request on a draft order is blocked before it reaches the handler, with an error message that explains itself instead of an anonymous 500.

tsallowed-actions.ts
import type { Action, Status } from './order-state'

const ACTIONS: Record<Status, Action[]> = {
  draft: ['submit', 'cancel'],
  pending: ['pay', 'cancel'],
  paid: ['ship', 'refund'],
  shipped: [],
  cancelled: [],
}

/** The single source of truth for both buttons and the API guard. */
export const allowedActions = (state: Status): Action[] => ACTIONS[state]

// component: allowedActions('paid') -> ['ship', 'refund'] -> render 2 buttons
// api:         if (!allowedActions(order.status).includes(action)) return 409
Buttons are no longer business knowledge buried in a template — that's where this refactor starts paying off.
Key pointAs long as you still see status === "paid" in a template, there's a machine that isn't being used.

04 — Who talks to whom

Structure

  • StateThe contract: which actions a state can answer, and which state each action leads to.
  • ConcreteState`draft`, `pending`, `paid`... Holds only its own behaviour; knows other states only by the name of the next one it returns.
  • Context (Order)Holds the current state, delegates actions to it, switches state if the state allows. Holds no transition rules.
  • TransitionTableThe machine written as data: `from → next[]`. Replaces class-per-state when behaviour is thin, and feeds the UI/API guard.
  • Client / UISends actions, asks `allowedActions(state)`. Never reads `status` to decide on its own.
  UI / API / cron
        │ action (submit | pay | ship | refund)
        ▼
┌──────────────────────────────────────────────┐
│ Context: Order                               │
│   state: OrderState                          │
│   apply(a) → state[a]?.(this) → state = next │  ← blocked here,
└───────────────────┬──────────────────────────┘    business logic
                    │ delegates, never checks status   sees nothing
      ┌─────────────┼──────────────┬──────────────┐
      ▼             ▼              ▼              ▼
 ┌─────────┐  ┌──────────┐  ┌──────────┐  ┌────────────┐
 │  draft  │  │ pending  │  │   paid   │  │  shipped / │
 │ submit  │  │ pay      │  │ ship     │  │ cancelled  │
 │ cancel  │  │ expire   │  │ refund   │  │ (no        │
 └────┬────┘  └────┬─────┘  └────┬─────┘  │  actions)  │
      │ pending    │ paid        │ shipped └────────────┘
      └───────────►└────────────►└──────────────► END

  Action not in the current state  →  error right at apply().

05 — Edit freely, run it right here

Try it: an order state machine blocking bad transitions

tsdemo.ts
type S = 'draft' | 'pending' | 'paid' | 'shipped' | 'cancelled'

// Table of valid transitions. Anything outside it is a BUG, not "a case we haven't written yet".
const NEXT: Record<S, S[]> = {
  draft: ['pending', 'cancelled'],
  pending: ['paid', 'cancelled'],
  paid: ['shipped', 'cancelled'],
  shipped: [],
  cancelled: [],
}

const LABEL: Record<S, string> = {
  draft: 'draft',
  pending: 'awaiting payment',
  paid: 'paid',
  shipped: 'shipped',
  cancelled: 'cancelled',
}

class Order {
  private state: S = 'draft'
  constructor(readonly id: string) {}

  get status(): string {
    return LABEL[this.state]
  }

  to(next: S): void {
    if (!NEXT[this.state].includes(next)) {
      console.log('  ✗ ' + this.id + ': ' + this.state + ' -> ' + next + ' (blocked)')
      return
    }
    console.log('  ✓ ' + this.id + ': ' + this.state + ' -> ' + next)
    this.state = next
  }
}

const myOrder = new Order('ORD-01')
myOrder.to('paid')      // skipping a stage
myOrder.to('pending')
myOrder.to('paid')
myOrder.to('shipped')
myOrder.to('cancelled') // the goods already left
console.log('  result: ' + myOrder.status)
console
  ✗ ORD-01: draft -> paid (blocked)
  ✓ ORD-01: draft -> pending
  ✓ ORD-01: pending -> paid
  ✓ ORD-01: paid -> shipped
  ✗ ORD-01: shipped -> cancelled (blocked)
  result: shipped

The same code runs on Bun: bun run demo.ts. Its output is checked automatically when the site is built.

06 — Honest about the cost

When to use it, when not to

Use it when

  • The object's behaviour changes with its state data, and the number of transitions is already ≥ 5 or still growing. Three states in a straight line? An enum is enough.
  • There are invalid transitions and their cost is real: refunding twice, shipping a cancelled order, publishing a post twice.
  • The same "what's allowed right now" rule has to be used in many places: UI, API guard, cron, worker. One source of truth, many askers.
  • You need an audit trail: who moved from which state to which, and when. The machine funnels everything into one function, so logging once is enough.
  • Transition rules are business logic that needs review by non-engineers: a state/transition table is readable, code inside if/else isn't.
  • You need idempotency for repeated commands (webhooks, retries, double-clicks): a duplicate transition isn't in the table, so it's blocked naturally.

Don't use it when

  • Over-engineering. Two states, one direction, no forbidden transitions? An enum plus an if is right. A machine is an investment that only pays off once the rules are complex or still growing.
  • A machine only means something if every path that changes state goes through it. One order.status = "paid" written straight to the DB in a migration file and that machine becomes a joke.
  • Pushing state logic into the UI forces the UI to know the business. Expose allowedActions(state), not state === "paid".
  • A state machine does not solve concurrency on its own. Two concurrent requests read the same state and both transition: you need a constraint at the storage layer (optimistic locking, UPDATE ... WHERE status = ...); the machine only handles valid vs invalid.
  • Using classes for 5 states with no behaviour of their own is creating 5 useless files. A data table is smaller, tests faster, and says the same thing.

07 — You have met it already, just not by name

In real code

WebSocket.readyState

A real browser API that is a state machine: CONNECTING → OPEN → CLOSING → CLOSED. Calling send() while readyState is CONNECTING throws InvalidStateError. That's deliberate design: invalid actions are blocked at the boundary, exactly in the spirit of the pattern.

useAsyncData / useFetch in Nuxt

This composable exposes status: "idle" | "pending" | "success" | "error", and components behave differently for each value (pending shows a skeleton, error shows retry). Rendering by state is the "behaviour depends on state" part; the transitions live inside the composable.

Reducers in Redux/Zustand

(state, action) => next is exactly a machine's transition function. This is where the reducer model shines: an invalid action usually returns the old state unchanged, so state can't fall into a combination that "has no transition".

XState / @xstate/vue

When the machine really grows (guards, side effects, nested machines, parallel machines), XState's declarative config + visualizer is worth more than a hand-written Record table. It's State + TransitionTable prepackaged for Vue/React.

Node.js streams

Calling res.end() twice throws ERR_STREAM_ALREADY_FINISHED; writing after destroy() throws. Node core keeps a small state machine for each stream and rejects operations at the wrong time, instead of a buffer silently losing data.

08 — Try it yourself

Exercise

Turn the following post workflow into a state machine that blocks bad transitions: `draft → review → approved → published`, plus `review → draft` (rejected) and `draft | review → archived`. Write a demo that runs `publish` on a post in `draft` (must be blocked), then runs the correct sequence.

Hints, open them one at a time:

  1. Write the Record<Status, Status[]> table first. published: [] and archived: [] are final states — don't forget them; if they're missing, TypeScript reports a missing key.
  2. One single to(next) function performs every transition; don't let calling code assign status directly.
  3. Add can(next): boolean so an API/page can ask first, for places that don't want an exception.

The transition table is the source of truth; to() blocks everything outside the table and throws an error that says exactly "from where to where". can() is the non-throwing version for the UI. The demo prints 4 lines: one blocked, three successful.

tsexercise.ts
type S = 'draft' | 'review' | 'approved' | 'published' | 'archived'

const NEXT: Record<S, S[]> = {
  draft: ['review', 'archived'],
  review: ['approved', 'draft', 'archived'],
  approved: ['published'],
  published: [],
  archived: [],
}

class Post {
  private state: S = 'draft'
  constructor(readonly slug: string) {}

  can(to: S): boolean {
    return NEXT[this.state].includes(to)
  }

  to(to: S): void {
    if (!this.can(to)) {
      console.log('  x ' + this.slug + ': ' + this.state + ' -> ' + to + ' blocked')
      return
    }
    console.log('  o ' + this.slug + ': ' + this.state + ' -> ' + to)
    this.state = to
  }
}

const p = new Post('state-pattern')
p.to('published')   // not reviewed yet -> must be blocked
p.to('review')
p.to('approved')
p.to('published')

09 — Read them in pairs to see the essence

Related patterns

  • StrategyNearly identical code, opposite intent: Strategy lets **the client choose** the algorithm, State lets **the state decide** and transition itself. Read this pair to see why meaning matters more than structure.
  • CommandWrap each transition in an object (`Pay`, `Ship`) and you can log, queue, retry and undo it. Command is how "actions" step out of the state machine, while State handles "allowed or not".
  • ObserverEvery time the machine changes state, notify so the UI updates, the audit log records it, and side effects run. State + Observer replaces every module polling `status` on its own.
  • MementoIf the machine keeps a history of states, `undo` = going back to the previous memento. Especially good for multi-step wizards and forms with a "Back" button.