LLD Hub
Learn

State Machine DesignModel 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

Order states (sketch)TypeScript
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

🚀 Now apply what you learned

Pick a problem above, write your solution, and get AI feedback on your design.

Start Practice →