State

Lets an object change its behaviour when its internal state changes, by putting each state's behaviour in its own class.

Why it matters

Objects with modes (an order that's paid or shipped, a machine that's idle or dispensing) often end up with if/else on a status field in every method, and invalid actions slip through.

The idea

A vending machine reacts differently to 'insert coin' when it's idle, when it already has money, or when it's sold out. Instead of an if/elif on a status variable inside every method, each state is a class that handles the events and decides the next state.

A traffic light: what happens on the next tick depends on whether it's red, amber or green, and each colour knows which comes next.

A traffic light has three simple states. Real systems can have many states and transitions, so draw the state diagram first, or the classes become hard to follow.

How it works

  1. Draw the state diagram: states as circles, events as arrows between them.
  2. Create one class per state, with one method per event.
  3. Each method does what's valid in that state, and may move the object to a new state.
  4. The main object holds its current state and forwards every event to it.
  5. An event that isn't valid in a state returns a clear 'not allowed' instead of doing something wrong.

Example

An order's life (created → paid → shipped → delivered, or cancelled), vending machines, elevators, network connections.

Key points

Common mistakes

Not true: In the State pattern, one big if/else on a status string decides what each method does.
In fact: That is the code the pattern removes. Each state becomes its own class, and the object passes every event to its current state.

In the interview

State moves each state's behaviour into its own class. A vending machine or an order then behaves correctly for its current state, and the transitions are explicit. It replaces an if/else on a status field in every method.

Part of Unit 6: Design patterns in the free System Design course.