State Diagrams
State diagrams (state machines) model object lifecycle: ticket valid → paid → used; elevator idle → moving → door open.
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.
stateDiagram-v2[*] --> IdleIdle --> Moving : requestFloorMoving --> Idle : arrived
Step-by-step explanation
- List states from domain (Created, Confirmed, Cancelled).
- List events triggering transitions (pay, cancel, expire).
- Mark invalid transitions to discuss with interviewer.
- Implement guard conditions in transition methods.
- Centralize transition logic in aggregate root.
- Log transitions for audit when required.
Syntax reference
State diagram notation:
- Label transitions with triggering event.
- Discuss unreachable states — good interview signal.
[*] --> CreatedCreated --> Confirmed : payCreated --> Cancelled : userCancelConfirmed --> Cancelled : refundCreated --> Expired : timeoutConfirmed --> [*]Cancelled --> [*]
Informative example
Booking ticket state machine with enum and guarded transitions:
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
Interview Prep
Practice concise answers, then expand each card for the explanation.
1BeginnerQuestionWhat is a state diagram?+
Answer
2BeginnerQuestionWhen use state diagram in LLD?+
Answer
3IntermediateQuestionEnum vs State pattern?+
Answer
4IntermediateQuestionHow handle invalid transition?+
Answer
5AdvancedQuestionDesign elevator state model.+
Answer
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.