← Questions

Design a vending machine

0
AmazonOO design

An object-oriented design interview question asked at Amazon. It tests object-oriented design.

Design a vending machine in code. It holds products in slots, accepts coins and notes, lets the customer select a product, takes payment, gives change and handles sold-out items. Model it with clear states so each action is only accepted when it makes sense.

Requirements

  • Functional: show products with slot codes and prices; accept coins and notes and keep a running balance; select a product: if it is sold out, say so; if the balance is short, ask for more; otherwise dispense the product and return change; cancel at any time to get the inserted money back; an operator restocks products and refills the change float.
  • Give change from the coins the machine actually holds, and refuse a sale (refunding the money) if exact change cannot be made.
  • Non-functional: money in integer cents; one customer at a time; adding a payment method (cards) does not rewrite the machine.

Clarifying questions

  • Which coins and notes are accepted?
  • Can the customer select first and pay after, or must they pay first?
  • What if the product jams and does not drop?
  • Can a customer buy several items with one balance?
  • Is card payment in scope now or later?

What a strong answer covers

  • Core classes: VendingMachine (the façade), Slot (code, product, count, price), Product, Inventory, CoinBox or CashRegister (denominations held, make_change(amount)), Money or Denomination, and a State interface with Idle, HasMoney, Dispensing and OutOfService.
  • The state pattern: each state accepts or rejects insert, select, cancel and dispense, so invalid sequences are handled in one place.
  • Change making from limited coins: greedy works for standard coin systems when supply is unlimited, but with limited coins you need a check (or a small search) and must refuse the sale if change is impossible.
  • Committing a sale only after dispensing and change both succeed, and refunding otherwise.
  • Tests: exact payment, change needed, no change possible, sold out, cancel with money in.

Follow-ups

  • Add card and mobile payments.
  • The machine reports stock and sales to a server for restocking routes.
  • Add promotions, such as a discount on a second item.

Where it's asked

What it tests

object-oriented design

Your canvas
Draw your answer hereBoxes, arrows and notes, saved for you to come back to.Sign in to start drawing