State lets an object change its behavior when its internal state changes. Instead of one class that checks a status field at the top of every method, each state becomes its own class with the same interface, and the object forwards every request to its current state object. Each state decides what a request means right now and which state comes next. It turns an implicit lifecycle (an order, a document, a connection, a vending machine) into an explicit state machine that the code itself enforces.
Think of it like
A ticket barrier
A metro ticket barrier answers the same two actions, tapping a card and pushing the arm, in different ways depending on its state. Locked, a tap opens it and a push does nothing. Unlocked, a push lets you through and locks it again. Out of service, it refuses both. The barrier does not look up a rule book on every push: it simply is in one state, and that state knows the answers and which state comes next. The barrier is the context, each mode is a state object, and tap and push are the events.
The problem
An online shop's Order can be paid, shipped and cancelled. The quickest version keeps the status in a string and starts every method with a guard on it. This is exactly the Before version in the visualizer above:
class Order {
private state = "placed";
pay() {
if (this.state !== "placed") throw new Error("refused");
this.state = "paid";
return "paid";
}
ship() {
if (this.state !== "paid") throw new Error("refused");
this.state = "shipped";
return "shipped";
}
cancel() {
if (this.state === "cancelled") throw new Error("refused");
this.state = "cancelled";
return "cancelled";
}
}
const order = new Order();
order.pay(); // "paid"
order.ship(); // "shipped"
order.cancel(); // "cancelled": a shipped order was cancelled!The cancel() guard was written when an order could only be placed or paid. Shipping came later, and nobody went back to cancel(). Run the Before version and the last call goes through: the parcel is on its way, yet the order says cancelled, and a refund job may pay the money back. Nothing in the code made the mistake visible.
- The lifecycle is nowhere. Which events are legal in which state is spread over the guards of every method. To answer "can a shipped order be cancelled?" you must read all of them, and the answer the code gives may not be the one the business intended.
- Every method must know every state. A new status (
refunded,on hold,returned) means re-reading each guard and each branch, and a missed one is a silent bug like the one above. - Behavior per state is scattered. Everything about a paid order (it can ship, it refunds on cancel) lives in three different methods, mixed with the rules of every other state.
- Guards grow into nested conditionals. Real orders add flags (
isGift,isPartiallyShipped), and the guards becomeif (state === "paid" && !onHold || ...)chains that are hard to test exhaustively.
The pattern
Intent: allow an object to alter its behavior when its internal state changes, so that the object appears to change its class. The behavior of each state lives in a class of its own, and the transitions between states become explicit.
- Context (
Order) - The object clients use. It holds the current state in a field (
state), forwards every event to it (pay()runsthis.state.pay(this)), and offers a way to switch states (setState(s)). It contains no status checks. - State (
State) - The interface with one method per event the context accepts:
pay,ship,cancel. Each method receives the context, so the state can act on it. - Concrete state (
Placed,Paid,Shipped,Cancelled) - One class per state. Each implements every event: it either does the work and moves the context on (
Placed.paycallsorder.setState(new Paid())) or refuses (Shipped.cancelthrows). - Transition
- Replacing the context's state object. In the classic form the current state performs it, so each state knows its possible successors.
The class diagram is the same shape as Strategy: a context with an association to an interface, and several implementations. The difference is in who swaps the object. A strategy is chosen by the client; a state is replaced by the states themselves as events arrive, and the client never has to know which one is current.
What the visualizer shows
- State machine strip (above the objects): the states as chips with the current one highlighted, the last transition, and the events allowed from here. It reads
order.stateat every step. In the Before version the same strip shows the lifecycle the business intended, and flags thecancel: shipped → cancelledmove in red because the machine has no such transition. - Objects at runtime:
orderwith its fieldstate = placed. Each transition creates the next state object (paid, thenshipped), and the arrow fromorder.statemoves to it. The old state objects stay in the drawing but nothing points to them any more. - Class diagram: when
orderforwardspay, theStateinterface lights up in violet (it declares the method) while the concrete state's method runs in amber. The class that answers changes with every transition, althoughOrderruns the same line each time. - Sequence of calls: each event is a call from the client to
order, then fromorderto the current state, then back from the state toorder.setState(...). That back-call is the transition. - Controls: press Play or step with the arrow buttons; the visualizer really runs the classes in the code panel and highlights the running line. Before / With State switches between the guard version and the pattern. Add Refunded applies the change request (a paid order that is cancelled becomes
Refunded) to the version shown, and the Change request panel beside the code counts what each version had to change.
Walkthrough
- 1
Create the context
new Order()runs the constructor, which createsplacedand stores it inorder.state. The strip showsPlacedas current; from there onlypayandcancellead anywhere. - 2
Forward the event
The client calls
order.pay().Order.paycontains one line,return this.state.pay(this), so the call goes toplaced.payis declared byState; the object is aPlaced, soPlaced.payruns. - 3
The state performs the transition
Placed.paycreates aPaidobject and callsorder.setState(paid). Thestatefield now points topaidinstead ofplaced, and the strip showspay: Placed → Paid. - 4
Same object, new behavior
The client holds the same
order, but the next event is answered by a different class.order.ship()goes topaid, whoseshipmoves the order toShipped. - 5
An event the state does not allow
order.cancel()now reachesShipped.cancel, which throwsrefused. The exception travels back throughorderto the client, which catches it. The order staysShipped: the rule lives in the one class that describes shipped orders, so there is no guard to forget. - 6
Compare with Before
Toggle Before and play the same three calls. The
cancel()guard only rejects"cancelled", so the string becomes"cancelled"and the strip marks the move as not allowed by the machine. - 7
Add Refunded (change request)
With Add Refunded applied, the client pays and then cancels.
Paid.cancelnow creates aRefundedobject, and a latership()is refused byRefunded. The new state's rules are all in its own class.
Before and after
Without the pattern
- One
Orderclass with astatestring and a guard in every method - The rules for one state are spread over all methods
- Nothing forces a method to handle a newly added state
- The lifecycle is implicit: you reconstruct it by reading guards
- Fewer classes; fine while there are two or three states
With State
Orderforwards each event to its current state object- Each state class holds every rule for that state
- Implementing
Stateforces a new state to answer every event - Transitions are explicit
setStatecalls inside the states - More classes, and the states know about each other
| Change request: add Refunded | Before | With State |
|---|---|---|
| Existing classes edited | 1 (Order) | 1 (Paid) |
| New classes | 0 | 1 (Refunded) |
| Lines changed in existing classes | 7 (+6 −1) | 4 (+2 −2) |
Read the numbers honestly: the pattern does not touch fewer classes here. Before edits one method of Order: the cancel() guard grows to reject "refunded" and a new branch turns a paid order into a refunded one. pay() and ship() happen to reject "refunded" already, but only because their guards are written as "anything except"; someone still had to check them. With State, Paid.cancel changes its target (two lines) and Refunded is a new class that must answer all three events, because the interface requires it. The edit lands where the rule belongs, and the old cancel() bug is still present in the Before version after the change.
Variations
| Who decides the next state | How | Trade-off |
|---|---|---|
| The states (classic GoF) | Each state calls order.setState(new Paid()) | Easy to extend with a new state; the states depend on each other, so the full lifecycle is spread over several classes |
| The context | States only do the work and report what happened; Order picks the successor | The lifecycle is in one place, but every new state edits the context again |
| A transition table | A map from (state, event) to the next state; the code looks it up | The machine is data you can print, validate, persist and draw; per-state behavior beyond the transition needs hooks |
State machines as tables
type Status = "placed" | "paid" | "shipped" | "cancelled" | "refunded";
type OrderEvent = "pay" | "ship" | "cancel";
const TRANSITIONS: Record<Status, Partial<Record<OrderEvent, Status>>> = {
placed: { pay: "paid", cancel: "cancelled" },
paid: { ship: "shipped", cancel: "refunded" },
shipped: {},
cancelled: {},
refunded: {},
};
function next(status: Status, event: OrderEvent): Status {
const to = TRANSITIONS[status][event];
if (to === undefined) throw new Error(`cannot ${event} when ${status}`);
return to;
}When states differ mostly in where they go next, not in what they do, a data-driven finite state machine like this is simpler than a class per state. Because the machine is data, a test can check it: every state is reachable from placed, final states have no exits, and every (state, event) pair has a decision. The same table can render a diagram for the product team. Libraries such as XState and workflow engines take this further: the machine is a declarative definition, and the library runs it, records the history and adds timers and nested states. The second implementation below is a complete table-driven machine with entry actions and persistence.
Entry and exit actions, guards, hierarchical states
- Entry and exit actions: work that runs whenever a state is entered or left, whatever the event: send the "shipped" email on entering
Shipped, stop a timer on leavingAwaitingPayment. With State classes, give the interface optionalonEnter(order)andonExit(order)and call them fromsetState, so no transition can forget them. - Guards: a transition that is allowed only if a condition holds (
shiponly if the address is verified). Keep the condition next to the transition, in the state method or the table entry, not in the client. - Hierarchical states: when several states share handling, nest them.
Paid,PackedandReadyToShipcan be substates ofActive, which handlescancelonce for all of them. This is the core idea of Harel's statecharts (1987) and of UML state machines; in class form, a parent state class that the substates extend does the same job.
Enums with behavior
enum OrderStatus {
PLACED {
OrderStatus pay() { return PAID; }
OrderStatus cancel() { return CANCELLED; }
},
PAID {
OrderStatus ship() { return SHIPPED; }
OrderStatus cancel() { return REFUNDED; }
},
SHIPPED, CANCELLED, REFUNDED;
// Default: refuse. Constants override only what they allow.
OrderStatus pay() { throw refuse("pay"); }
OrderStatus ship() { throw refuse("ship"); }
OrderStatus cancel() { throw refuse("cancel"); }
IllegalStateException refuse(String event) {
return new IllegalStateException(
"cannot " + event + " when " + this);
}
}
// The context: status = status.pay();State objects usually have no fields of their own, so one instance per state is enough. Java expresses that directly: each enum constant can override methods, and the JVM creates each constant once. Here each method returns the next state instead of calling setState, which keeps the enum free of any reference to the context. The default methods double as the "refuse unless allowed" rule. Sharing one instance per state is Flyweight applied to State (the states are intrinsic, the order is the extrinsic data), and GoF notes that state objects are often Singletons.
Illegal transitions: throw, ignore or report
| Policy | Use it when | Example |
|---|---|---|
| Throw | The caller should never send this event in this state; it is a bug or a race to surface | ship() on a cancelled order throws, and the API answers 409 Conflict |
| Ignore (no-op) | Repeating the event is harmless and common | A second click on Pay while the payment is in flight; a door that is already locked |
| Return a result | The caller expects refusals as a normal outcome | tryCancel() returns false and the UI shows "too late to cancel" |
| Record and alert | Refusing silently would hide a real-world problem | A shipment event arrives for a refunded order: keep the state, log it and open a ticket |
In real code
| Where | States | What the pattern buys |
|---|---|---|
| TCP connections (the GoF book's own example) | TCPConnection delegates to TCPEstablished, TCPListen, TCPClosed | open(), close() and acknowledge() mean different things in each state; the protocol's states are listed in RFC 793 |
| UI components | A form or button that is idle, loading, success or error | Rendering and allowed actions follow one explicit status instead of several booleans (isLoading && !isError) that can contradict each other |
| Workflow and statechart engines | XState in JavaScript, AWS Step Functions, Spring Statemachine | The machine is declared as data; the engine runs transitions, timers and nested states, and keeps the history |
| Game AI | An enemy that patrols, chases, attacks or flees | Each behavior is its own state with entry actions (play an animation) and its own rules for when to switch |
Java's Thread.State | NEW, RUNNABLE, BLOCKED, WAITING, TIMED_WAITING, TERMINATED | An enum that names the lifecycle states; getState() reports the current one. A plain enum like this is often the first step before behavior moves into the states |
When to use it, and when not to
Reach for State when
- Several methods branch on the same status field
- The object has a real lifecycle with rules about which events are legal when
- Each state has enough behavior to fill a class
- New states are likely (refunds, holds, returns)
- Illegal transitions are costly bugs (money, shipments, safety)
Keep it simpler when
- There are two or three states and one or two methods care
- States differ only in the next state: use a transition table
- New events arrive more often than new states
- The behavior is a chosen algorithm, not a lifecycle (that is Strategy)
- A library already owns the lifecycle (a workflow engine, a UI state library)
State vs similar patterns
| Pattern | What the object represents | Who switches it | Typical shape |
|---|---|---|---|
| State | The current mode of one object's lifecycle | The states (or the context) as events arrive; the client usually never chooses | States know their successors; often stateless and shared |
| Strategy | An interchangeable algorithm | The client or configuration, from outside | Strategies are independent and unaware of each other |
| Command | One request (an action plus its arguments) | Whoever creates it; an invoker runs, queues or undoes it | Many command objects over time; often stored in a history |
| Memento | A snapshot of an object's data | The originator saves and restores it | Data to bring back later, not behavior |
| Flyweight | Shared intrinsic data | A factory hands out shared instances | Stateless state objects are flyweights: one Paid serves every order |
Implementation
The visualizer's scenario as a complete program, with the change request applied: an OrderState interface, one class per state, and an Order context that forwards each event to its current state. Placed and Paid perform transitions; a refused event throws. The C++ version shares one instance per state because states have no fields, which also avoids a state deleting itself in the middle of its own method.
from __future__ import annotations
from abc import ABC, abstractmethod
from typing import Callable
class IllegalTransition(Exception):
pass
class OrderState(ABC):
name = ""
def refuse(self, event: str) -> None:
raise IllegalTransition(f"cannot {event} a {self.name} order")
@abstractmethod
def pay(self, order: Order) -> None: ...
@abstractmethod
def ship(self, order: Order) -> None: ...
@abstractmethod
def cancel(self, order: Order) -> None: ...
class Placed(OrderState):
name = "placed"
def pay(self, order: Order) -> None:
order.set_state(Paid())
def ship(self, order: Order) -> None:
self.refuse("ship")
def cancel(self, order: Order) -> None:
order.set_state(Cancelled())
class Paid(OrderState):
name = "paid"
def pay(self, order: Order) -> None:
self.refuse("pay")
def ship(self, order: Order) -> None:
order.set_state(Shipped())
def cancel(self, order: Order) -> None:
# The change request: a paid order that is cancelled is refunded.
order.set_state(Refunded())
class Final(OrderState):
"""Shipped, Cancelled and Refunded refuse every event."""
def pay(self, order: Order) -> None:
self.refuse("pay")
def ship(self, order: Order) -> None:
self.refuse("ship")
def cancel(self, order: Order) -> None:
self.refuse("cancel")
class Shipped(Final):
name = "shipped"
class Cancelled(Final):
name = "cancelled"
class Refunded(Final):
name = "refunded"
class Order:
"""The context: no status checks, it forwards every event."""
def __init__(self, order_id: str) -> None:
self.order_id = order_id
self._state: OrderState = Placed()
@property
def status(self) -> str:
return self._state.name
def set_state(self, nxt: OrderState) -> None:
print(f"{self.order_id}: {self._state.name} -> {nxt.name}")
self._state = nxt
def pay(self) -> None:
self._state.pay(self)
def ship(self) -> None:
self._state.ship(self)
def cancel(self) -> None:
self._state.cancel(self)
def attempt(action: Callable[[], None]) -> None:
try:
action()
except IllegalTransition as e:
print(f"refused: {e}")
if __name__ == "__main__":
a = Order("A1")
a.pay() # A1: placed -> paid
a.ship() # A1: paid -> shipped
attempt(a.cancel) # refused: cannot cancel a shipped order
b = Order("B2")
b.pay() # B2: placed -> paid
b.cancel() # B2: paid -> refunded
attempt(b.ship) # refused: cannot ship a refunded order
print(a.status, b.status) # shipped refundedKey takeaways
- State gives each state of an object its own class behind one interface; the context holds the current state object and forwards every event to it, so its methods contain no status checks.
- Transitions are explicit: a state replaces itself with
order.setState(new Paid()). The same object then answers the next event with a different class. - Each state must answer every event, which makes illegal transitions a deliberate decision (throw, ignore or report) instead of a forgotten guard.
- Adding a state is cheap (a class plus edits to the states that lead to it); adding an event is expensive (every state class gains a method). In the visualizer's "Add Refunded" request, Before edits
Orderby 7 lines, With State editsPaidby 4 and addsRefunded. - When states differ only in where they go next, a transition table (or an engine such as XState) is simpler than a class per state.
- State and Strategy share a class diagram; in State the states switch themselves and know each other, in Strategy the client chooses and strategies are independent.
Common pitfalls
- Leaving status checks in the context: an
if (state instanceof Shipped)inOrderrebuilds the conditional the pattern removed. Every decision about an event belongs to the state that receives it. - Mutable data in state objects. Order data (amount, address) belongs in the context; keep states stateless so they can be shared and so a transition never loses data.
- Persisting the state object itself, or a class name taken from untrusted input. Store a known state name, map it back through a fixed table, and reject anything else.
- Using State for two or three states with one method each. An enum with an exhaustive
switch, or a small transition table, is easier to read until the per-state behavior grows. - Forgetting entry and exit work on some paths. If every transition goes through
setState, putonEnter/onExitcalls there instead of repeating them in each state method.
Interview tips
- In LLD rounds (vending machine, elevator, parking ticket, booking) draw the state diagram first: states as boxes, events as labeled arrows. Then map it to one class per state and one method per event, and say which transitions are illegal and what happens on them.
- Expect "State vs Strategy". Answer with who switches the object (the states versus the client) and whether the variants know each other.
- Mention the alternatives and when you would pick them: an enum with a transition table for simple lifecycles, a workflow engine for long-running processes, and shared stateless state instances (Flyweight or Singleton) to avoid allocating on every transition.
Real-world applications
- Order, payment, shipment and subscription lifecycles in e-commerce and billing.
- Document and approval workflows: draft, in review, approved, published, archived.
- Network protocol connections, such as the TCP connection states in the GoF book.
- UI components and screens with idle, loading, success and error states.
- Vending machines, elevators, traffic lights and other device controllers.
- Game characters and AI that patrol, chase, attack or flee.
Test yourself
In the State version of the order, which code decides that a paid order becomes shipped when ship() is called?
Related topics
Finished this lesson? Track it to see your progress on the roadmap.