Skip to content
LLD Learn/Behavioral Patterns
Browsing as a guest. Sign in to save your progress and earn XP as you complete chapters.

State

4 min read

You'll learn to

  • -Model an object whose behavior changes with its internal state without a giant switch statement
  • -Implement transitions as a set of classes, each owning only the behavior valid in that state
  • -Read a state-transition table, and spot a missing transition
  • -Say when State is overkill, and how it differs from Strategy

State lets an object alter its behavior when its internal state changes, appearing to change its class. In practice, it replaces a giant switch statement on a status field with a set of classes, one per state, each of which owns exactly the behavior that is valid in that state.

An Analogy: The Traffic Light

The same event, the timer expiring, does completely different things depending on the light's current color: green changes to yellow, yellow to red, and red to green. Nobody writes one giant routine that asks what color am I and then branches. Each color knows what it does and what comes next. State captures exactly that: the object has a current state, every request is handled by that state, and the state decides the next one.

The Problem: State-Dependent Behavior as Conditionals

The pattern this replaces - branching on state everywhere
class VendingMachine:
    def __init__(self):
        self.state = "idle"

    def insert_coin(self):
        if self.state == "idle":
            self.state = "has_coin"
        elif self.state == "has_coin":
            print("Coin already inserted")
        elif self.state == "dispensing":
            print("Please wait, dispensing in progress")
        # every new state means editing every method that branches on state

The State Pattern Version

Each state owns its own transitions - no central switch statement
class VendingMachineState(ABC):
    @abstractmethod
    def insert_coin(self, machine: "VendingMachine") -> None: ...
    @abstractmethod
    def select_item(self, machine: "VendingMachine") -> None: ...

class IdleState(VendingMachineState):
    def insert_coin(self, machine):
        machine.state = HasCoinState()
    def select_item(self, machine):
        print("Insert a coin first")

class HasCoinState(VendingMachineState):
    def insert_coin(self, machine):
        print("Coin already inserted")
    def select_item(self, machine):
        machine.state = DispensingState()

class DispensingState(VendingMachineState):
    def insert_coin(self, machine):
        print("Please wait, dispensing in progress")
    def select_item(self, machine):
        print("Already dispensing")

class VendingMachine:
    def __init__(self):
        self.state: VendingMachineState = IdleState()   # delegates every call to current state

    def insert_coin(self) -> None:
        self.state.insert_coin(self)

    def select_item(self) -> None:
        self.state.select_item(self)

Reading the Transitions

A state-transition table is the best way to check a design, and the one for the sketch above is short. A missing arrow is a bug, and this sketch has one:

  • -Idle: insert_coin moves to HasCoin; select_item is refused.
  • -HasCoin: insert_coin is refused; select_item moves to Dispensing.
  • -Dispensing: insert_coin and select_item are refused. Nothing ever moves it out.

Nothing moves the machine out of Dispensing, so after one sale it would be stuck. A real design needs a transition back to Idle (or to a sold-out state) once dispensing finishes, as the vending machine design chapter does. Drawing the table is how you find that in an interview before the interviewer does.

Why This Scales Better Than the Conditional Version

Adding a new state (OutOfStockState) in the conditional version means finding and editing every method that branches on state.state string values - easy to miss a spot. In the State pattern version, adding OutOfStockState means writing one new class that implements the shared interface; VendingMachine itself never changes, and no existing state class needs to be touched. This is the exact same Open/Closed win Strategy provides, applied specifically to state-dependent behavior.

Design Choices and Pitfalls

  • -State objects with no data of their own can be shared: one IdleState instance can serve every machine. Keep the data (balance, selected item) in the context.
  • -Where the transitions live: in each state (as here) keeps each class self-contained but spreads the flow around; a single transition table in the context shows the whole flow at a glance.
  • -Overkill: an object with two states and one method that branches on a boolean does not need five classes. Reach for State when several methods each branch on the same status, and when new states are likely.
  • -Test each state class on its own: for every state and every event, assert the result and the next state.

Revisit the Strategy chapter's distinction: the structure here looks nearly identical to Strategy (an interface, a holder, delegation), but the states themselves drive transitions (IdleState.insert_coin() sets machine.state = HasCoinState()) rather than a caller choosing the "algorithm" from outside.

Interview Signal is part of Pro

See a real weak answer next to a real strong one for this exact topic.

Quiz is part of Pro

Test what you just read with a short quiz, and bank the XP.

Discussion0

Join the Discussion

Sign in to leave comments, reply to others, or like insights.

Sign In to ScaleDojo

No comments yet. Be the first to start the thread!