State

Intermediate · 18 min read · Low-Level Design, Behavioral Patterns

Behaviour that changes with internal state — the backbone of many machine-coding problems.

The idea in plain words

Some objects behave differently depending on their current state. Cancelling an order is easy before it ships and impossible after. Instead of an if (status == ...) in every method, each state becomes a small class that knows how to handle each action and which state comes next.

Finite-state machines

An object with a lifecycle is a finite-state machine: a finite set of states, events that trigger transitions, and rules for which transitions are allowed.

The problem: conditionals everywhere

With 5 states and 5 operations, logic is spread across 25 switch branches. Adding a state means editing every method.

The solution

Move each state's behaviour into its own class implementing a common State interface. The context (the machine) holds a reference to the current state object and delegates every operation to it. States trigger transitions by telling the context which state comes next.

Design decisions

If states hold no data of their own (data lives in the context), share one instance per state — even across many machines (they're effectively flyweights/singletons). If states carry data (e.g., a countdown), create new instances on transition.

Pros and cons

State vs Strategy

Both delegate behaviour to an object behind an interface. The difference:

Interview questions

  • How does the State pattern differ from a switch statement on an enum?
  • Where should state transition logic live?
  • How do you make a state machine thread-safe?

Further reading

Key takeaways

  • Model lifecycle-driven objects as finite-state machines; draw the diagram first.
  • State moves each state's behaviour into its own class; the context delegates to the current state.
  • Decide where transitions live (states or a table) and reject invalid transitions explicitly.
  • Strategy is chosen from outside; State changes from inside as events occur.

Previous: Observer · Next: Command