Learn

Architecture & pattern guides

Read the idea, build it on a Grid, prove it in a challenge. Short, practical guides — illustrated with RodGrid's own nodes — on system design, design patterns, flow modeling, and how to get the most out of the app.

All articles

State

Let an object change its behavior when its internal state changes, by delegating to one object per state, and decide who owns the moves from one state to the next.

Five methods, one question

A chat app's mobile client keeps a Connection object to the chat server, and at any moment that connection is in one of four situations: disconnected, connecting, open or reconnecting. The class records which one in a status field. Its five methods, connect(), send(), close(), socketOpened() and socketClosed(), each begin with switch (this.status).

Take send(message). When the connection is open, it writes the message to the socket. While connecting or reconnecting, it adds the message to an outbox that is flushed once the socket opens, so a reply typed in a tunnel goes out when the signal comes back. When disconnected, because the user signed out, it rejects the message with an error. socketClosed() has answers of its own: a connection that was open or connecting schedules another attempt and becomes reconnecting, and a connection the user closed on purpose stays closed. Four states times five methods is twenty small decisions, filed by method.

Then the mobile team asks for a fifth state. When the app goes to the background, the client should close its socket and only reconnect when the user comes back: suspended. The developer adds the new case to send(), connect(), close() and socketOpened(). The one in socketClosed() is missed, and that switch falls through to its default, which in this codebase means "try again". So suspending the app closes the socket, the close arrives in socketClosed(), and the client opens a new connection straight away, the opposite of what suspension was for.

Each switch was correct for the states it knew. The code is organized by method, while this change arrived as a state, and a new state has to be threaded through every switch by hand with nothing to say that one was skipped.

Give each state its own class

Turn the arrangement around. Define one interface, ConnectionState, with a method for each thing that can happen to a connection, and write one class per state that implements it. OpenState.send() writes to the socket, ReconnectingState.send() adds to the outbox, DisconnectedState.send() rejects. Connection keeps a reference to its current state object instead of a status string, and each of its methods becomes one line that hands the call over: send(message) { this.state.send(this, message); }.

That arrangement is the State pattern. The object whose behavior varies, Connection, is the Context, and it delegates to a current state object; each concrete state encapsulates the behavior for its state. The big switch disappears, because the question it asked on every call is now answered by which object this.state points at.

Connection delegates to its current state

Connection depends only on the interface. Disconnected and Suspended implement it too; they are left out to keep the picture small.

Replay the request for suspension. SuspendedState is a new class, and since it implements ConnectionState it has to answer every method. In Java or TypeScript, when no interface method is optional or has a default or inherited implementation, the compiler rejects the class until every method exists (it checks presence, not behavior), so the missed socketClosed() from the switch version cannot go missing quietly. Here it does nothing: the socket closed because the client closed it.

Suspension also brings two new events, the app going to the background and coming back, and an event is a new method on ConnectionState that every state class must implement. That cost is real, and it is the mirror image of the switch: one switch per method made a new method cheap and a new state expensive, and one class per state does the opposite.

Where the transitions live

Something has to replace ConnectingState with OpenState when the socket opens. In the usual form of the pattern the current state does it: ConnectingState.socketOpened(conn) flushes the outbox and calls conn.setState(new OpenState()). Each state decides its own successors, so what comes after Open sits next to what Open does.

Each state chooses the next one

Every arrow is a transition made by the state it leaves. Only the main ones are drawn: close(), a failed attempt and going to the background from other states are left out.

In exchange, concrete states know each other: OpenState creates a SuspendedState, and removing a state means finding every class that switches to it. The Context can own the transitions instead, as a table that gives the next state for each current state and event; Connection looks up the row after each event and swaps the object. That is also a valid State design. The states then do only their own work, and the whole lifecycle can be read in one place, at the cost of keeping the table and the classes in step.

Wherever the transitions live, data that must survive a change of state, such as the outbox, belongs in the Context. A state object created on entry can hold what only matters while that state lasts, such as the retry timer that ReconnectingState cancels if close() arrives first.

Designing the lifecycle itself, which events exist and which conditions guard each move, is modelling work done before any of these classes: State machines: states, events and guards covers it, and State machines as flows draws the same kind of lifecycle with flowchart nodes.

When a switch is still the better code

Five classes and an interface replace one field and a few switch statements, and that only pays when the switch statements hurt. A Download that is queued, running or done, and uses that only to choose an icon and enable a button, is clearer as an enum and one switch. The same holds when states are few and settled, when one or two methods vary by state, or when new operations arrive more often than new states. State earns its classes when several methods branch on the same field and states keep being added, and then it has to be finished: state classes alongside a status field that some methods still switch on cost both designs at once, and the field and the state object can disagree about where the connection is.

Who picks the object

On a diagram, State looks like Strategy: a Context holding an interface, with interchangeable implementations behind it. The difference is in intent: strategies are interchangeable ways to do one task, usually chosen from outside, while states carry the behavior tied to each stage of the object's lifecycle and are usually replaced from inside, by the current state or the Context's table, as events arrive.

Open the State Pattern Challenge and draw Connection, or a lifecycle of your own: a Component node for the Context, a Port / Interface node for the state interface, and a State node for each concrete state. The Context's delegation arrow should go to the interface, not to a concrete state, and the concrete states should be joined by arrows labelled with the events that move them. Before you submit, follow one event through the drawing, such as the socket closing while the connection is open: find the state that handles it and the arrow it takes. If the Context decides, one central rule that picks the next state, a table or a switch, is fine; check that the decisions about what each method does have not spread back into Connection's methods, and that adding a state also updates the transitions.

Practice this