State
Intent
Let an object change its behavior when its internal status changes, by delegating each request to its current state object.
Motivation
A music player behaves differently stopped, playing, and paused: pressing play from stopped starts the track, from paused it resumes, and pressing pause while stopped does nothing. A nest of status flags in the player turns every button into a branch maze. Giving each status its own object — stopped, playing, paused — lets the player delegate the press to whichever state is active, and transitions become explicit moves between states.
Structure
flowchart LR Player[Player Context] --> St[State] St --> Stopped[Stopped] St --> Playing[Playing] St --> Paused[Paused] Stopped --> Playing Playing --> Paused Paused --> Playing
- Context (Player) — holds the current state and forwards button presses to it.
- State — the shared press-handling contract.
- Concrete states (Stopped, Playing, Paused) — implement presses for that status and trigger transitions.
Consequences
- Benefit: each status’s rules live alone; transitions are explicit and new states plug in cleanly.
- Cost: more small classes, and transitions scattered across states can be hard to survey — keep a transition list in the docs.
Basic Recap
State lets an object alter its behavior by delegating to an object representing its current state. Each state defines which events are valid and which transitions follow, while the context holds shared data and the current state. This replaces scattered conditionals about lifecycle status with localized behavior. State differs from Strategy because transitions belong to the object’s lifecycle rather than a caller freely selecting an algorithm.
Complex Scenario
A deployment controller moves through draft, awaiting-approval, executing, completed, failed, and rolling-back states. Approval is meaningful only while awaiting approval, retry is allowed only under a failure policy, and cancellation has different effects before and after execution begins. Each state handles controller events and returns explicit transitions plus actions. The controller persists its state and version so other services observe one coherent lifecycle.
Edge cases
- Concurrency: Approval and cancellation arriving together must be serialized by a version check or per-deployment lock; both transitions cannot commit from the same starting version.
- Ordering: A delayed worker-started event after cancellation is stale and should be recorded or rejected according to policy, not blindly accepted.
- Retries: Duplicate approval or completion events need idempotent handling so notification and infrastructure actions are not repeated.
Side effects should be emitted as durable actions tied to a committed transition; running them inside an in-memory state object can leave state and reality apart.
Sketch (illustrative pseudocode, not runnable):
DeploymentController.handle(event):
current = store.loadForUpdate(this.id)
decision = current.state.handle(current, event)
if decision.invalid:
return rejectionWithCurrentState(current)
store.commitIfVersionMatches(current.version, decision.nextState)
actionOutbox.appendAll(decision.actionKeys, decision.actions)
return acceptedTransition(decision)
AwaitingApproval.handle(context, Approve):
requireApproverRole(Approve.actor)
return Transition(EXECUTING, actions = [StartWorkerOnce(context.id)])
When to Use / When Not to Use
Use when:
- Behavior depends on internal status with explicit allowed transitions (players, orders, connections).
- Status-flag branches are spreading through many methods.
Avoid when:
- Behavior is picked once by the caller rather than evolving internally — that is Strategy, not State.
Examples
examples/elixir/state/examples/dart/state/examples/go/state/examples/rust/state/
Expected outcome: pressing play then pause prints each state change in order.
Anti-pattern / Failure Mode
-
Misuse: A state machine with two states and no transitions — an enum would do.
-
Review signal: Transition logic scattered across states instead of owned explicitly.
-
Misuse symptom: State objects coexist with public status flags and ad hoc assignments elsewhere, so behavior and stored status disagree. A state class that directly performs long network calls also turns lifecycle decisions into untestable side-effect bundles.
-
Review signal: Watch for transition logic duplicated in controllers, states reaching into unrelated services, and events accepted without checking the current version. Logs showing impossible transitions or repeated action keys indicate that the abstraction exists but the transition boundary is not atomic or idempotent.
Related
- Strategy — object transitions itself vs caller injects the variant.
- Template Method — status-driven behavior vs fixed skeleton.
- Explicit State Ownership — one owner per state.
Exercise
Add a “stop” action returning to Stopped from either Playing or Paused. Then make pause-from-Stopped print “already stopped” instead of changing state.
Self-check
- Who triggers transitions?
Answer
The concrete state objects (or the context on their instruction) — transitions ride on behavior, not on external if-chains. - State vs Strategy: what differs?
Answer
Strategy’s variant is chosen by the caller; State’s active variant changes itself as the object’s status evolves. - Where is the transition map?
Answer
Distributed across state objects here; for many states, centralize it in a table on the context instead.