State Machine Design — Model complex lifecycle with states
States + events + transitions — tabulate before you code. · Invalid transitions should fail loudly.
Watch
Watch, then scroll down for code and practice.
In code
type OrderState = "NEW" | "PAID" | "SHIPPED";
class Order {
private state: OrderState = "NEW";
pay() {
if (this.state !== "NEW") throw new Error("invalid");
this.state = "PAID";
}
ship() {
if (this.state !== "PAID") throw new Error("invalid");
this.state = "SHIPPED";
}
}📘 Key ideas
When to use
Any object with a lifecycle: orders (Placed→Packed→Shipped→Delivered), ATMs (Idle→CardInserted→Authenticated), elevators.
State pattern
Extract each state into a class. The context delegates behaviour to the current state. Transitions are explicit.
Transition table
Draw a table: rows = current states, columns = events, cells = next states. This becomes your implementation map.
Invalid transitions
Throw an exception or return an error for invalid state transitions. Never silently ignore them.
🧠 Practice — Apply What You Learned
Parking Lot System
Design a parking lot system that can handle multiple floors, different vehicle types, and …
ATM Machine
Design an ATM system that handles card authentication, balance inquiry, cash withdrawal, a…
Tic Tac Toe Game
Design a Tic Tac Toe game supporting 2 players (human or AI) on an N×N board.…
Ride Sharing System (Uber/Ola)
Design a ride sharing platform where riders request rides and drivers accept them.…
Elevator System
Design an elevator control system for a building with multiple elevators and floors.…
Hotel Booking System
Design a hotel room booking platform with availability search, pricing, and reservation ma…
Event Ticketing System
Design a large-scale event ticketing platform (like Ticketmaster) with high concurrency su…
🚀 Now apply what you learned
Pick a problem above, write your solution, and get AI feedback on your design.
Start Practice →