State

Letting an object change behaviour when its internal state changes — finite state machines, state classes vs transition tables, an order lifecycle example, and when enums suffice.

Intermediate 2 min readLesson 17 of 24

Intent: allow an object to alter its behaviour when its internal state changes. The object will appear to change its class.

Many objects are really finite state machines: an order (created → paid → shipped → delivered), a TCP connection, a vending machine, a document workflow, a traffic light. Their methods mean different things — or are illegal — depending on the current state.

payshipdelivercancelcancel (refund)CreatedPaidShippedDeliveredCancelled

The problem: conditionals in every method

Java
void ship() {
    if (status == CREATED) throw new IllegalStateException("not paid");
    else if (status == PAID) { /* ship */ status = SHIPPED; }
    else if (status == SHIPPED) throw new IllegalStateException("already shipped");
    else if (status == CANCELLED) throw new IllegalStateException("cancelled");
    ...
}
// ...and the same ladder in pay(), cancel(), deliver()

Every new state means editing every method. Rules for one state are scattered across the whole class.

The pattern: one class per state

The context (Order) holds a reference to a state object and delegates to it. Each state class implements only the behaviour valid for that state and decides the next state.

interface OrderState {
    default OrderState pay(Order o)     { throw illegal("pay"); }
    default OrderState ship(Order o)    { throw illegal("ship"); }
    default OrderState deliver(Order o) { throw illegal("deliver"); }
    default OrderState cancel(Order o)  { throw illegal("cancel"); }
    String name();
    private IllegalStateException illegal(String action) {
        return new IllegalStateException("cannot " + action + " when " + name());
    }
}

final class Created implements OrderState {
    public OrderState pay(Order o)    { o.capturePayment(); return new Paid(); }
    public OrderState cancel(Order o) { return new Cancelled(); }
    public String name() { return "CREATED"; }
}
final class Paid implements OrderState {
    public OrderState ship(Order o)   { o.createShipment(); return new Shipped(); }
    public OrderState cancel(Order o) { o.refund(); return new Cancelled(); }
    public String name() { return "PAID"; }
}
final class Shipped implements OrderState {
    public OrderState deliver(Order o) { return new Delivered(); }
    public String name() { return "SHIPPED"; }
}
final class Delivered implements OrderState { public String name() { return "DELIVERED"; } }
final class Cancelled implements OrderState { public String name() { return "CANCELLED"; } }

class Order {
    private OrderState state = new Created();
    void pay()     { state = state.pay(this); }
    void ship()    { state = state.ship(this); }
    void deliver() { state = state.deliver(this); }
    void cancel()  { state = state.cancel(this); }
    String status() { return state.name(); }
    void capturePayment() {...} void createShipment() {...} void refund() {...}
}

Stateless state objects (like these) can be shared singletons; states that carry data (e.g. retry counts) are created per transition.

Alternative: a transition table

For simple machines where states don't have much distinct behaviour, a table is clearer than classes and can be validated, visualised or loaded from config:

TypeScript
type Status = "CREATED" | "PAID" | "SHIPPED" | "DELIVERED" | "CANCELLED";
type Action = "pay" | "ship" | "deliver" | "cancel";

const transitions: Record<Status, Partial<Record<Action, Status>>> = {
  CREATED:   { pay: "PAID", cancel: "CANCELLED" },
  PAID:      { ship: "SHIPPED", cancel: "CANCELLED" },
  SHIPPED:   { deliver: "DELIVERED" },
  DELIVERED: {},
  CANCELLED: {},
};

function next(s: Status, a: Action): Status {
  const to = transitions[s][a];
  if (!to) throw new Error(`invalid: ${a} from ${s}`);
  return to;
}
payshipdelivercancelNEWPAIDSHIPPAID––CANCELLED–SHIPPED–CANCELLED––DELIVERED–
The same machine as a state × action table.
ApproachBest when
Enum + switch2–3 states, little behaviour
Transition tableMany states, behaviour mostly "allowed or not"; config-driven workflows
State classesEach state has substantial, distinct behaviour
State machine libraryHierarchical/parallel states, guards, timers (XState, Spring Statemachine)

Persisting state

In real systems the state lives in a database column (status = 'PAID'). Load the column, map it to the state object, apply the transition, and save with an optimistic check (UPDATE … SET status='SHIPPED' WHERE id=? AND status='PAID') so two concurrent requests can't both ship the order.

Key takeaways
  • State pattern: each state is an object; the context delegates and the state picks the next state.
  • Eliminates repeated conditionals and keeps each state's rules together.
  • Illegal transitions become explicit errors.
  • Transition tables are simpler for "allowed or not" machines; libraries handle complex ones.
  • Persist the state and guard transitions against concurrent updates.