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.
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.
The problem: conditionals in every method
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() {...}
}class OrderState:
name = "?"
def pay(self, order): raise self._illegal("pay")
def ship(self, order): raise self._illegal("ship")
def deliver(self, order): raise self._illegal("deliver")
def cancel(self, order): raise self._illegal("cancel")
def _illegal(self, action):
return RuntimeError(f"cannot {action} when {self.name}")
class Created(OrderState):
name = "CREATED"
def pay(self, order):
order.capture_payment(); return Paid()
def cancel(self, order):
return Cancelled()
class Paid(OrderState):
name = "PAID"
def ship(self, order):
order.create_shipment(); return Shipped()
def cancel(self, order):
order.refund(); return Cancelled()
class Shipped(OrderState):
name = "SHIPPED"
def deliver(self, order): return Delivered()
class Delivered(OrderState): name = "DELIVERED"
class Cancelled(OrderState): name = "CANCELLED"
class Order:
def __init__(self): self.state: OrderState = Created()
def pay(self): self.state = self.state.pay(self)
def ship(self): self.state = self.state.ship(self)
def deliver(self): self.state = self.state.deliver(self)
def cancel(self): self.state = self.state.cancel(self)interface OrderState {
readonly name: string;
pay?(o: Order): OrderState;
ship?(o: Order): OrderState;
deliver?(o: Order): OrderState;
cancel?(o: Order): OrderState;
}
const Delivered: OrderState = { name: "DELIVERED" };
const Cancelled: OrderState = { name: "CANCELLED" };
const Shipped: OrderState = { name: "SHIPPED", deliver: () => Delivered };
const Paid: OrderState = {
name: "PAID",
ship: (o) => { o.createShipment(); return Shipped; },
cancel: (o) => { o.refund(); return Cancelled; },
};
const Created: OrderState = {
name: "CREATED",
pay: (o) => { o.capturePayment(); return Paid; },
cancel: () => Cancelled,
};
class Order {
state: OrderState = Created;
private transition(action: keyof Omit<OrderState, "name">) {
const fn = this.state[action];
if (!fn) throw new Error(`cannot ${action} when ${this.state.name}`);
this.state = fn(this);
}
pay() { this.transition("pay"); }
ship() { this.transition("ship"); }
cancel() { this.transition("cancel"); }
createShipment() {} refund() {} capturePayment() {}
}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:
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;
}| Approach | Best when |
|---|---|
| Enum + switch | 2–3 states, little behaviour |
| Transition table | Many states, behaviour mostly "allowed or not"; config-driven workflows |
| State classes | Each state has substantial, distinct behaviour |
| State machine library | Hierarchical/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.
- 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.