पाठ 19 / 25

State and State Machines

Behaviour that depends on the current state.

Explicit states and transitions

Intent: let an object change its behaviour when its internal state changes, as if it changed class. The GoF version gives each state its own class implementing the same interface. In everyday code the more common form is an explicit finite state machine: a fixed set of states, the events each one accepts, and the allowed transitions. Orders (pending, paid, shipped, delivered, cancelled), subscriptions, document approval flows and UI request states (idle, loading, success, error) are classic examples. The benefit is that illegal transitions become impossible or loud, instead of being scattered boolean flags like isPaid && !isCancelled. Libraries such as XState exist for complex statecharts; a typed transition table is enough for many cases.

Model lifecycles and processing chains

More behavioural patterns for lifecycles, algorithms with fixed skeletons, handler chains and traversal.

Three ideas: state machines, template method and chains, iterator and visitor.
Figure 7.1 — State transitions, handler chains and tree traversal.

An order state machine

A transition table makes illegal moves explicit.

type OrderState = 'pending' | 'paid' | 'shipped' | 'delivered' | 'cancelled';
type OrderEvent = 'pay' | 'ship' | 'deliver' | 'cancel';

const transitions: Record<OrderState, Partial<Record<OrderEvent, OrderState>>> = {
  pending:   { pay: 'paid', cancel: 'cancelled' },
  paid:      { ship: 'shipped', cancel: 'cancelled' },
  shipped:   { deliver: 'delivered' },
  delivered: {},
  cancelled: {},
};

function transition(state: OrderState, event: OrderEvent): OrderState {
  const next = transitions[state][event];
  if (!next) throw new Error(`Cannot ${event} an order that is ${state}`);
  return next;
}

let state: OrderState = 'pending';
state = transition(state, 'pay');      // 'paid'
state = transition(state, 'ship');     // 'shipped'
// transition(state, 'cancel') throws: shipped orders cannot be cancelled here

Draw it first

Sketch states as circles and events as arrows before coding. Missing arrows reveal unhandled cases, and the diagram doubles as documentation for product and support teams.

त्वरित जाँच: What is the main benefit of modelling an order as a state machine?

  • It allows any state change at any time
  • It makes the database faster
  • It removes the need for tests
  • Allowed transitions are explicit, so illegal ones are rejected
Answer

Allowed transitions are explicit, so illegal ones are rejected — Explicit transitions replace scattered flags.