LOAD-BEARINGfree
Low-level design dojoTier 13 · unit 24 of 31

Vending machine

Accepts coins and notes, dispenses a product, returns change. Must handle insufficient funds, sold-out items, cancellation, and running out of change.

The machine behaves differently when Idle, HasMoney, Dispensing and OutOfService. Best structure?

  • State pattern with one class per state
  • A status enum checked at the top of every method
  • Separate machines per state
  • A queue of pending actions
Why

State. Inserting a coin means something different in each mode, and several transitions are illegal. State classes make "dispense while idle" unrepresentable rather than merely guarded.

The user selects a product, but the machine cannot make exact change. What is the correct behaviour?

  • Dispense and round down in the machine’s favour
  • Refuse the selection before dispensing and refund
  • Dispense and owe the user
  • Dispense the nearest cheaper product
Why

Check the full transaction is completable before committing to any part of it. This is the physical-world version of validating an invariant before a partial commit — and the reason the dispense step should be atomic with the change calculation.

Assign each responsibility.

Track stock count per slot
Inventory
Hold coin denominations available for change
CashBox
Decide which actions are currently legal
MachineState
Coordinate the purchase across the other three
VendingMachine
Compute a change combination from available coins
CashBox
Why

The machine is a coordinator, not a doer. Change computation is a real algorithm — greedy fails for some denomination sets, so it needs its own home where it can be tested and swapped independently.