Vending Machine · 9003
A medium low-level design interview question on state, encapsulation, validation. 8 scenario tests.
SYNOPSIS
interviewer: Design a vending machine.
A snack machine that takes coins, sells from slots and gives change. About 35 minutes.
QUESTIONS TO ASK
Interviews start vague on purpose. Strong candidates ask before they draw; in the studio the interviewer answers these and the answers become your requirements.
- Which coins does it take?
- How are products organised?
- How is change given?
- What can go wrong when buying?
- Can the customer cancel?
- Does the machine behave differently depending on whether money is inserted?
- Card or phone payments?
- Several items in one purchase?
DESCRIPTION
The full statement, as the studio shows it at the implement step.
Design the controller of a snack vending machine: it takes coins, sells products from slots and gives change.
requirements
- Slots have a code ("A1", "B3"…), a product name, a price in cents and a quantity. stock(code, name, price, qty) adds a slot or restocks it (a restock adds qty and may change the name and price).
- Accepted coins: options.coins, default [5, 10, 25, 100] (cents).
- insert(coin) adds to the balance and returns the new balance.
- select(code) sells one item and returns { item, change }, where change is the coins handed back, largest first, using the fewest coins.
- cancel() returns the whole balance as coins (same rule) and resets.
- state is "idle" (balance 0) or "has-money".
errors (the message must contain the quoted text; the balance is kept)
- insert() of a coin that is not accepted: "rejected coin"
- select() of a code that was never stocked: "unknown slot"
- select() of a slot with quantity 0: "sold out"
- select() with too little money: "insert <n> more", e.g. "insert 15 more"
Assume the machine has an unlimited supply of every accepted coin for change, so change can always be made with the accepted coins.
think about
- Each method behaves differently depending on the state. Where does that branching live: in every method, or in state objects?
- Adding a "maintenance" state where every action is refused.
GRADING
The studio runs the interview in seven steps (clarify, entities, class diagram, patterns, sequence, implement, review) and a coach grades each one live: the core objects you found, the relations between them (ownership vs. use, the right end of the diamond), responsibilities, whether your patterns really have the shape of the pattern, and a sequence diagram of the main use case. Then you implement it in JavaScript and run its 8 scenario tests in your browser. The review gives a score out of 100, a hire signal and a reference design to compare.
FOLLOW-UPS
What the interviewer asks when you finish early:
- The coin supply is limited: change can fail. Refuse the sale before taking the money, and choose coins so a sale is never lost needlessly.
- Card payments: a second payment method with a pending/authorized state.