Notes
The problem
Here is the naive version. The ride has a status enum, and every method switches on it. Cancel has one switch, assign driver has another, start trip another, end trip another. The rules for one situation, say driver assigned, are scattered across four methods. When product adds a new status, like driver arrived, you must find and edit every switch, and missing one branch is a silent bug.
void cancel() {
switch (status) {
case SEARCHING -> status = CANCELLED;
case ASSIGNED -> { fee = 50;
status = CANCELLED; }
case ON_TRIP -> fail("end trip");
default -> fail("already over");
}
}
// assignDriver, startTrip, endTrip:
// the same switch, four times The idea
The idea in one sentence: put the behaviour for each situation in its own class, and let the object delegate every call to whichever one is current. When the situation changes, the object swaps in a different state object. From the outside it looks as if the ride changed its class: the same method call now behaves completely differently. Instead of grouping code by method, we group it by situation.
- put the behaviour for each
- situation in its own class,
- and let the object delegate to
- whichever one is current
- from outside, the object seems
- to change its class when its
- situation changes
The structure
The participants. RiderApp is the client that taps buttons. Ride is the context: it holds the trip details and a reference to its current state. RideState is the state interface, with one method per action: assign driver, start trip, end trip and cancel. Searching, DriverAssigned, OnTrip, Finished and Cancelled are the concrete states. The client only ever talks to the ride. It never sees the state classes.
Transition table
Before writing classes, write the transition table. Searching plus assign driver moves to driver assigned. Searching plus cancel is free. Driver assigned plus start trip moves to on trip, and cancel there costs a fee of fifty. On trip plus end trip charges the fare and moves to finished, and cancel is refused. Finished and cancelled are terminal states that refuse everything. Every cell in this table becomes one method in one class.
- Searching + assign -> Assigned
- Searching + cancel -> Cancelled
- Assigned + start -> OnTrip
- Assigned + cancel -> Cancelled
- (fee 50)
- OnTrip + end -> Finished
- (fare by distance)
- OnTrip + cancel -> refused
- Finished, Cancelled:
- terminal, refuse everything
The code: interface
The interface has one method per action, and each method receives the ride. A neat trick: every method has a default body that refuses the action with a clear message. So a state class only overrides the actions it actually allows. The terminal states, finished and cancelled, override nothing at all. Without the defaults, each state would repeat the same boring refusals.
interface RideState {
String label();
default void assignDriver(Ride r,
String driver) {
r.refuse("assign a driver"); }
default void startTrip(Ride r) {
r.refuse("start the trip"); }
default void endTrip(Ride r, int km) {
r.refuse("end the trip"); }
default void cancel(Ride r) {
r.refuse("cancel"); } } The code: a state
Here is one concrete state, driver assigned. It allows two actions. Start trip moves the ride to on trip. Cancel charges the cancellation fee and moves the ride to cancelled. Everything a developer needs to know about this situation is in one short class. Adding a new rule here cannot break the searching or on trip behaviour, because they live in other files.
final class DriverAssigned
implements RideState {
public String label() {
return "driver on the way"; }
public void startTrip(Ride r) {
r.moveTo(new OnTrip()); }
public void cancel(Ride r) {
r.charge(CANCEL_FEE);
r.moveTo(new Cancelled()); }
} The code: context
The context is almost boring, which is the point. The ride starts in searching. Each public method simply forwards to the current state, passing itself. It also offers small helpers the states use, like move to, which logs the transition and swaps the state, and charge, which records money. The ride holds the data. The states hold the rules.
private RideState state = new Searching();
void cancel() { state.cancel(this); }
void startTrip() { state.startTrip(this); }
void moveTo(RideState next) {
log(state.label() + " to "
+ next.label());
state = next;
} Run-through
Let us follow one ride. The app calls assign driver. The ride forwards it to searching, which records the driver and moves the ride to driver assigned. Next, start trip goes to driver assigned, which moves to on trip. Then end trip with twelve kilometres goes to on trip, which computes the fare and moves to finished. If the app now presses cancel, finished refuses it. The app never wrote a single if statement about status.
Who owns transitions
Who decides the next state? In our version, each state decides, by calling move to. That keeps the rule and the transition together, but states know about each other. The alternative is for the context, or a transition table, to decide, which keeps the whole graph in one place and makes it easy to check. Both are valid designs. In an interview, pick one and say why.
- states decide (our version):
- + rules and moves together
- - states know each other
- context or table decides:
- + whole graph in one place
- + easy to draw and verify
- - rules split from moves
- both are fine: say which
- and why
Stateless states
Notice that our state classes have no fields. The driver name and the fare live in the ride. That means one instance of each state can be shared by every ride, as static constants or even as an enum that implements the interface. If a state needs its own data, like a retry counter or a timer, create a fresh instance on every transition instead. Either way, keep the data the whole ride needs in the context.
- our states hold no data:
- the ride holds driver, fare
- so one instance each is fine:
- static final constants,
- or an enum that implements
- the interface
- if a state needs its own data
- (a timer, a retry count),
- create a new one each time
State vs switch
Is a switch always wrong? No. With two or three states and one or two actions, a switch expression is shorter and perfectly readable, and adding the State pattern would be over engineering. Move to state classes when there are four or more states, when the rules inside each state keep growing, or when new states arrive often. The cost of the pattern is more classes and logic spread across files, so it must earn its place.
- two or three states
- one or two actions
- rules that rarely change
- move to State classes when:
- four or more states
- rules per state are growing
- new states arrive often
- Java 17 switch + sealed types
- keeps small cases readable
State vs Strategy
State and Strategy have the same class diagram: a context holding a reference to an interface. The difference is intent. With Strategy, the client chooses one algorithm, like a fare rule for surge pricing, and it rarely changes during the object's life. The strategies do not know each other. With State, the object switches its own state as events happen, and states often know which state comes next. Ask who changes it and when.
- Strategy: the client picks
- one algorithm, e.g. a
- FareRule; it rarely changes
- and strategies do not know
- each other
- State: the object changes its
- own state as events happen;
- states often know the next
- state
In Java and elsewhere
The Java standard library has few textbook examples of this pattern. You meet it in business code instead: order and payment workflows, document review from draft to approved, game characters that idle, run and jump, and network connection handlers. There are also libraries, such as Spring Statemachine, that build the transition graph for you. Do not confuse it with the thread state enum, which only names states and holds no behaviour.
- order and payment workflows
- document review: draft,
- in review, approved
- game characters: idle,
- running, jumping
- network connection handlers
- libraries such as Spring
- Statemachine
- note: Thread.State is just
- an enum, not this pattern
In LLD interviews
State is a favourite in machine coding rounds. The vending machine is the classic: idle, has money and maintenance. An elevator moves between idle, moving up, moving down and doors open. An A T M has no card, card inserted and pin verified. Order lifecycles and traffic signals fit too. Listen for words like mode, lifecycle or only allowed when. Draw the transition table on the board first, then name the state classes.
- vending machine: idle, has
- money, maintenance
- elevator: idle, moving up,
- moving down, doors open
- ATM: no card, card in, pin ok
- traffic signal phases
- order: placed, packed,
- shipped, delivered
- parking ticket lifecycle
Mistakes to avoid
Common mistakes. Leaving if statements on status inside the context, which defeats the pattern. Letting states reach into the context's fields instead of calling small helpers. Forgetting to define what happens for an invalid action, so it silently does nothing. Forgetting terminal states, so a finished ride can be cancelled. Using the pattern for two simple states. And skipping the transition table, which is the real specification.
- context still checks status
- with if statements
- states change fields of the
- context directly
- no rule for invalid actions
- forgetting terminal states
- state classes for two states
- not drawing the table first