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

Non-functional requirements

From version 1 to the final design

  1. Version 1: one item, exact coins only.
  2. Version 2: several items, an inventory, and change-making.
  3. Version 3: a State class for each mode, plus cancel and refund.
  4. Version 4: card payments as a strategy, admin restocking, and recovery after a power cut.

The design, step by step

  1. Idle → select an item → ItemSelected → insert money → HasMoney (once paid ≥ price) → Dispensing → give change → Idle.
  2. Cancel while in ItemSelected or HasMoney → refund → Idle.
  3. An item with no stock left → SoldOut for that item.

Deep dives

Common mistakes

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.