Vending Machine: low-level design

Design a vending machine. A person inserts money, picks a product, and the machine dispenses it and returns change. It must handle sold-out items, too little money and cancellations.

Stage 1: Products and stock

Model what the machine sells and how much is left.

We have a machine in mind but nothing for it to sell. A `Product` has a name and a price. An `Inventory` maps slot codes to products and quantities, and can say whether a slot has stock, hand one out, or be restocked. Stock is its own class so the machine never touches slot details. All 'is it in stock?' logic lives in one place. Prices live on the product, not the slot. If you want per-machine pricing, move the price to the slot.

Stage 2: A machine that works, badly

Build the obvious version and see where it hurts.

We need something that takes money and gives products. `VendingMachine` keeps a balance, a state string and the inventory. Each action starts with `if state == ...`. It works for two or three situations. But `insertMoney`, `select` and `cancel` each need a branch per state, so adding 'out of service' means editing every method. This is the version most people write first. Naming its weakness (branches multiply with every new state) is exactly why the next stage exists.

Stage 3: Each situation becomes a state

Replace the if statements with state objects.

Every method repeats the same state checks, and a new situation means editing all of them. A `VendingState` interface with the three actions. `IdleState`, `HasMoneyState` and `DispensingState` each implement them. The machine forwards every action to its current state object. This is the **State** pattern. 'Select' in the idle state says 'insert money first'. In the has-money state it checks stock and price, then moves to dispensing. Each class is short and answers one situation. More classes, but each one is tiny. The reward comes when you add a state: it is one new class, not edits scattered through three methods.

Stage 4: Change and errors

Return correct change and refuse bad requests clearly.

Change is a single number, so impossible amounts look valid, and sold-out or underpaid choices have no clear outcome. A `ChangeCalculator` turns an amount into real coins from what the machine holds. `HasMoneyState` now checks, in order: is it in stock, is there enough money, can we make change. Each failure keeps the money and says why. Checking before acting means money and stock never end up out of step: nothing is dispensed unless every check passes. Pulling change into its own class lets you swap the algorithm (fewest coins, or save large coins). Greedy change (always the biggest coin) is simple and works for normal coin sets, but fails for odd denominations or when coins run out. A smarter strategy fits behind the same class.