Design a vending machine
Design a vending machine that sells items, accepts coins and gives change.
Why interviewers ask it
It's the clearest test of the State pattern: every action means something different depending on the machine's state.
Functional requirements
- Select an item, insert money, get the item and any change.
- Cancel and get a refund.
- Restock items and coins (admin).
Non-functional requirements
- Never hand out an item without enough money, and never lose money.
- Clear behaviour in every state.
From version 1 to the final design
- Version 1: one item, exact coins only.
- Version 2: several items, an inventory, and change-making.
- Version 3: a State class for each mode, plus cancel and refund.
- Version 4: card payments as a strategy, admin restocking, and recovery after a power cut.
The design, step by step
- Idle → select an item → ItemSelected → insert money → HasMoney (once paid ≥ price) → Dispensing → give change → Idle.
- Cancel while in ItemSelected or HasMoney → refund → Idle.
- An item with no stock left → SoldOut for that item.
Deep dives
- Change-making: the greedy method works for UK coins when you have plenty of each, but with limited coins it can fail even when exact change is possible (60p with one 50p and three 20p coins). Use dynamic programming, or refuse the sale.
- Keep money in whole pence (integers), never floats, so that sums are exact.
- Power cut mid-sale: record the transaction before dispensing, so it can be recovered.
Common mistakes
- An if/else on a status string in every method.
- Taking money for an item that's sold out.
- Assuming change can always be made.
Not true: Change: as long as the machine holds some coins, the right change can be given.
In fact: With limited coins some amounts cannot be made: 30p of change is impossible with only 20p and 50p coins. Check that change can be made before taking the money.
In the interview
I'd model the machine with the State pattern — Idle, ItemSelected, HasMoney, Dispensing, SoldOut — so every action is only valid in the right state. Money is in pence; change is worked out from the coins actually available, and the sale is refused if exact change isn't possible.
Part of Unit 7: Low-level design questions in the free System Design course.