State

Letting an object change its behaviour when its internal state changes.

An object behaves differently depending on what mode it's in โ€” an order that's draft, paid, shipped or cancelled; a document in review; a vending machine mid-transaction. The version everyone writes first is a status enum plus a conditional at the top of every method, and it decays predictably: adding a fifth state means finding every one of those conditionals, and missing one is a bug that only shows up in that state.

State makes each mode a class implementing a common interface, so behaviour lives with the state it belongs to and the object delegates to whichever it currently holds. Adding a state adds a class. The pay-off is that illegal transitions become expressible: ShippedOrder.cancel() can throw or return a refusal, rather than relying on a conditional somewhere remembering to check.

Two things to get right. Transitions have to have an owner โ€” either each state returns the next one, or a central table maps (state, event) to state; scattering both is how you get a machine nobody can draw. And the confusion with Strategy is worth pre-empting: same structure, but a strategy is chosen by the caller and stays put, while a state replaces itself as a consequence of handling a request. If your objects transition themselves, it's State.

What they ask, and what to say

What does State replace, and why is that better?

A status enum plus the same conditional at the top of every method. Making each state a class puts behaviour next to the state it belongs to, so adding a state means adding a class instead of finding every switch and hoping you got them all.

Why they ask: Naming the specific smell it removes is more convincing than reciting intent.

How does State help with illegal transitions?

Each state only implements what's legal from there, so Shipped.cancel() can refuse explicitly. The rule lives in the state rather than in a conditional somewhere that has to remember to check.

Why they ask: Interviewers probe transitions because that's where real state machines go wrong.

Who owns transitions โ€” the states or the context?

Pick one. States returning the next state keeps each rule local but scatters the map; a central transition table makes the machine readable in one place at the cost of coupling. Doing both is what makes a state machine nobody can follow.

Why they ask: A design judgement question with no single right answer โ€” they're listening for whether you know it's a choice.

Where it shows up

Designs on this site that reach for State naturally, rather than for decoration.