Low-Level Design Tutorial 0/42 lessons ~6 min read Lesson 20

    State Diagrams

    State diagrams (state machines) model object lifecycle: ticket valid → paid → used; elevator idle → moving → door open.

    Course progress0%
    Focus
    10 guided sections
    Practice signal
    Examples included
    Career prep
    Interview Q&A included

    Introduction

    State diagrams (state machines) model object lifecycle: ticket valid → paid → used; elevator idle → moving → door open. When behavior depends on current state, explicit states prevent illegal transitions.

    Interviewers ask state diagrams for elevators, vending machines, booking tickets, and TCP-style connections. Java enums plus transition methods implement them cleanly.

    Confusing state with class type leads to class explosion — one Order class with state field is usually enough.

    Understanding the topic

    Key concepts

    • States: discrete modes object can occupy.
    • Transitions: events moving between states with guards.
    • Initial and final pseudo-states.
    • Entry/exit actions on state (optional).
    • State pattern when behavior varies per state.
    • Enum-backed state machines for simple LLD.
    text
    stateDiagram-v2
    [*] --> Idle
    Idle --> Moving : requestFloor
    Moving --> Idle : arrived

    Step-by-step explanation

    1. List states from domain (Created, Confirmed, Cancelled).
    2. List events triggering transitions (pay, cancel, expire).
    3. Mark invalid transitions to discuss with interviewer.
    4. Implement guard conditions in transition methods.
    5. Centralize transition logic in aggregate root.
    6. Log transitions for audit when required.

    Syntax reference

    State diagram notation:

    • Label transitions with triggering event.
    • Discuss unreachable states — good interview signal.
    text
    [*] --> Created
    Created --> Confirmed : pay
    Created --> Cancelled : userCancel
    Confirmed --> Cancelled : refund
    Created --> Expired : timeout
    Confirmed --> [*]
    Cancelled --> [*]

    Informative example

    Booking ticket state machine with enum and guarded transitions:

    java
    public final class Booking {
    public enum Status { CREATED, CONFIRMED, CANCELLED, EXPIRED }
    private final String id;
    private Status status;
    public Booking(String id) {
    this.id = id;
    this.status = Status.CREATED;
    }
    public void confirm() {
    if (status != Status.CREATED) throw new IllegalStateException(status.name());
    status = Status.CONFIRMED;
    }
    public void cancel() {
    if (status == Status.CONFIRMED || status == Status.CREATED) {
    status = Status.CANCELLED;
    return;
    }
    throw new IllegalStateException("cannot cancel " + status);
    }
    public Status status() { return status; }
    }

    IllegalStateException documents invalid transitions — matches state diagram guards.

    Real-world use

    Real-world applications

    • Elevator and vending machine controllers.
    • Order and booking lifecycle.
    • Game phases (Snake and Ladder turn states).

    Best practices

    • One authoritative state field per aggregate.
    • Transition methods enforce guards centrally.
    • Use enum for finite known states.
    • State pattern when behavior differs heavily per state.
    • Document timeout transitions explicitly.

    Common mistakes

    • Separate class per state for simple enums (overkill).
    • Public setState bypassing guards.
    • Missing terminal states.
    • Concurrent transitions without locking.

    Advanced interview questions

    Q1BeginnerWhat is a state diagram?
    Shows states of an object and events causing transitions between them.
    Q2BeginnerWhen use state diagram in LLD?
    When object behavior depends on lifecycle mode — booking, elevator, connection.
    Q3IntermediateEnum vs State pattern?
    Enum + methods for simple machines; State pattern when each state has complex behavior.
    Q4IntermediateHow handle invalid transition?
    Reject in domain method with clear exception or Result type.
    Q5AdvancedDesign elevator state model.
    States: Idle, Moving, DoorOpen; events: arrive, openDoor, closeDoor, move; controller owns transition table.

    Summary

    State diagrams capture object lifecycle and events. Guard transitions in domain methods. Enums suffice for many interview problems. State pattern for complex per-state behavior. Pair with class diagram for context.

    Ready to mark this lesson complete?Track your journey across the entire course.