Design a Vending Machine
You'll learn to
- -Model the machine as a State-pattern state machine and write down its transitions
- -Trace one purchase through the states with real numbers, including change
- -Fix two weaknesses in the first draft: money as floats, and one item running out taking the whole machine out
- -Be ready for the follow-ups: cancel, a jam, exact change and concurrency
A vending machine is the cleanest possible showcase for the State pattern covered earlier in this course. Its behavior is obviously state-dependent: what happens when you press "select" is completely different depending on whether money has been inserted. That makes State a natural fit rather than a forced one.
Step 1: Requirements and the State Set
Assume: the machine holds an inventory of items with prices, accepts coins one at a time, lets the user select an item once enough money is inserted, dispenses the item and any change, and can be out of stock for a specific item or fully sold out. That maps to four core states: Idle, HasMoney, Dispensing, and OutOfStock (or SoldOut).
Before any code, write the transitions down, because in an interview the table is the design. Idle goes to HasMoney when a coin arrives. HasMoney stays in HasMoney for more coins, and goes to Dispensing when a valid item is selected with enough money. Dispensing goes back to Idle when it finishes, or to OutOfStock when the last unit of something sells. Every other combination of state and action is refused with a clear message.
Step 2: The State Interface and Context
class VendingMachineState(ABC):
@abstractmethod
def insert_coin(self, machine: "VendingMachine", amount: float) -> None: ...
@abstractmethod
def select_item(self, machine: "VendingMachine", item_code: str) -> None: ...
@abstractmethod
def dispense(self, machine: "VendingMachine") -> None: ...
class VendingMachine:
def __init__(self, inventory: dict[str, "Item"]):
self.inventory = inventory
self.balance = 0.0
self.selected_item: "Item | None" = None
self.state: VendingMachineState = IdleState()
def insert_coin(self, amount: float) -> None:
self.state.insert_coin(self, amount)
def select_item(self, item_code: str) -> None:
self.state.select_item(self, item_code)
def dispense(self) -> None:
self.state.dispense(self)Step 3: Each State Owns Its Own Valid Transitions
class IdleState(VendingMachineState):
def insert_coin(self, machine, amount):
machine.balance += amount
machine.state = HasMoneyState()
def select_item(self, machine, item_code):
print("Insert coins first")
def dispense(self, machine):
print("Nothing to dispense")
class HasMoneyState(VendingMachineState):
def insert_coin(self, machine, amount):
machine.balance += amount # allow adding more coins
def select_item(self, machine, item_code):
item = machine.inventory.get(item_code)
if not item or item.quantity == 0:
print("Item unavailable")
return
if machine.balance < item.price:
print("Insufficient funds")
return
machine.selected_item = item
machine.state = DispensingState()
class DispensingState(VendingMachineState):
def insert_coin(self, machine, amount):
print("Please wait, dispensing in progress")
def select_item(self, machine, item_code):
print("Already dispensing")
def dispense(self, machine):
item = machine.selected_item
item.quantity -= 1
change = machine.balance - item.price
print(f"Dispensing {item.name}, change: {change}")
machine.balance = 0.0
machine.selected_item = None
machine.state = OutOfStockState() if item.quantity == 0 else IdleState()Tracing One Purchase
Say item A1 is Chips, price 1.25, with 2 left. The user inserts 1.00 and then 0.50, selects A1, and the machine dispenses:
- -Insert 1.00: Idle becomes HasMoney and the balance is 1.00.
- -Insert 0.50: HasMoney stays HasMoney and the balance is 1.50.
- -Select A1: the item exists and has stock, and 1.50 is at least 1.25, so the item is selected and the state becomes Dispensing.
- -Dispense: quantity goes from 2 to 1, the change is 1.50 minus 1.25, which is 0.25, the balance resets to zero, and the machine returns to Idle.
Two Weaknesses in the First Draft
The first is money as floating-point numbers. In Python, 0.1 + 0.2 is 0.30000000000000004, so a machine that tracks change in floats will sooner or later give the wrong coin. The standard answer is to store money as integer cents, and say so out loud:
print(0.1 + 0.2) # 0.30000000000000004
balance_cents = 100 + 50 # integers are exact
change_cents = balance_cents - 125
print(change_cents) # 25The second is a wrinkle in the draft above. When the last unit of one item sells, DispensingState moves the whole machine to OutOfStock, even though the other items are still available. An empty item is already handled where it belongs, in select_item, which refuses an unavailable item. The machine as a whole should be SoldOut only when every item's quantity is zero. Saying this unprompted shows you have thought about the design, not just copied a pattern.
Why This Design Absorbs Follow-Ups Cleanly
Notice that DispensingState transitions directly to OutOfStockState() when the last unit of an item sells out - inventory-driven state transitions fall out naturally from the pattern rather than needing a separate "check inventory everywhere" concern bolted on. If the interviewer asks "what if a user cancels and wants a refund mid-transaction," the answer is a new method on the interface (cancel()) implemented per state. HasMoneyState.cancel() refunds and returns to Idle, while IdleState.cancel() and DispensingState.cancel() can each define their own behavior, likely a no-op or a rejection. No existing transition logic needs to change.
Follow-Ups to Be Ready For
- -Cancel and refund: a cancel() method on the state interface, with each state deciding what it means. HasMoney refunds the balance and returns to Idle; Idle and Dispensing refuse.
- -A physical jam while dispensing: add a Faulted state that refunds the customer, blocks new sales and can only be left by a technician. A new state, with no change to the others.
- -Exact change only: when the machine cannot make change, HasMoney refuses a selection that would need it and tells the user.
- -Concurrency: one customer at a time is part of the model. If actions can arrive from two threads, protect the machine with a lock so a coin and a selection never interleave.
Compare this design explicitly against the "if state == X" conditional version from the State pattern chapter when you present it - naming that comparison out loud is exactly the kind of principle-grounded reasoning interviewers are listening for.
Interview Signal is part of Pro
See a real weak answer next to a real strong one for this exact topic.
Quiz is part of Pro
Test what you just read with a short quiz, and bank the XP.
Forge Level 36: Vending Machine asks you to implement balance tracking, stock, and the invalid-selection/out-of-stock/insufficient-balance guard chain from this chapter, graded by running your actual code against real test cases.
Discussion0
Join the Discussion
Sign in to leave comments, reply to others, or like insights.
No comments yet. Be the first to start the thread!