OOD & LLD Reference/Classic LLD: Resource & State Machines

Vending Machine

State pattern classic — Idle, HasMoney, Dispensing, SoldOut — inventory management, coin handling, and change calculation.

3/5Overview: 25m

Problem framing

A vending machine accepts coins, lets users select items, dispenses product, returns change. Tests state machine modeling, inventory, and whether you reach for State pattern vs spaghetti if/else.

StateAllowed actionsTransitions
IdleinsertCoincoin → HasMoney
HasMoneyinsertCoin, selectItem, returnCoinsselect → Dispensing; return → Idle
Dispensing(internal) dispense + changedone → Idle or SoldOut
SoldOutreturnCoins onlyrestock → Idle

Core classes

VendingMachine holds current State, Inventory, CoinStore. Each state implements VendingState with insertCoin(), selectItem(), dispense(). Inventory maps slotId → Product with quantity. CoinStore tracks inserted value and available change denominations.

Why State over enums + switch

With 4 states, a switch works — but say: "State pattern localizes transition logic; adding MaintenanceMode is one new class, not editing every branch." Map transitions on the whiteboard before writing classes.

Change-making subproblem

Greedy works for canonical coin systems (US quarters); arbitrary denominations may need DP — mention only if asked. For LLD, CoinStore tracks counts per denomination and makeChange(amount) returns coins or fails.

Senior-level signal

Walk through insufficient change: machine rejects selection or refunds — state where invariants matter. Mention that selectItem() should validate inventory and sufficient credit atomically. Defer: multi-item selection, card payment, admin restock API.

Where this goes next

Library Management System introduces catalog vs inventory separation and reservation workflows — a richer entity model with M:N relationships.

Further Reading

Practice Tasks (Optional)

Design or implement locally in any language — no autograding. Focus on class structure, extensibility, and being able to explain trade-offs out loud.

  • Draw state diagram and class mapping

    Draw states and transitions for a vending machine. Map each state to a class implementing a common interface. Implement selectItem() and insertCoin() transitions on paper.

    30m