Model a Vending Machine With the State Pattern

Last updated: November 29, 2026

Quick Overview

Design classes for a vending machine that accepts coins, dispenses a selected item with change, supports cancel with refund, and rejects invalid actions depending on its current state.

Google
Software Engineering Fundamentals
Software Engineer
Google
November 29, 2026
Software Engineer
Phone Screen
Software Engineering Fundamentals
Easy

0

0

0 solved


Design classes for a vending machine that accepts coins, dispenses a selected item with change, supports cancel with refund, and rejects invalid actions depending on its current state.

A common object-oriented warm-up in Google loops for new grads and early-career engineers. The interviewer looks at whether behavior that depends on state lives in state objects rather than a growing if-else chain, and whether money is handled in integer cents.

What the Interviewer Expects
  • Identifies states (idle, has money) and the events each accepts
  • Moves state-specific behavior into separate classes
  • Uses integer cents to avoid floating-point money errors
  • Validates coins, stock, and sufficient balance with clear errors
  • Keeps the machine's public API small and stable
Key Topics to Cover
state pattern
object-oriented design
finite state machine
integer money
encapsulation
How to Approach This
  1. Apply SOLID principles. Single Responsibility makes code testable, Open/Closed makes it extensible.
  2. Choose data structures based on access patterns, not familiarity.
  3. Prefer immutable data and message passing over shared mutable state for concurrency.
  4. Design APIs with RESTful conventions, versioning, meaningful errors, and pagination from day one.
Possible Follow-up Questions
  • How would you add a maintenance state that blocks all purchases?
  • How do you return change when the machine has a limited coin inventory?
  • How would you test every state transition systematically?
Sharpen Your Skills on Codemia

Practice similar problems with our interactive workspace, get AI feedback, and track your progress.

Practice System Design Problems
Sample Answer
Requirements
  • Accept coins of 5, 10, 25, 100 cents; reject others.
  • select(slot) dispenses if stocked and paid, returning change.
  • cancel() refunds the balance.
  • Invalid actions for the current state raise...
High-Level Design

VendingMachine is the context holding stock, balance, and a State object. Each public method delegates to the current state. Idle accepts coins only; HasMoney accepts more coins, selection, or...


Submit Your Answer
Markdown supported