Skip to content

Case study: vending machine

Difficulty: Intermediate

Key concepts

  • state machines
  • std::variant states
  • exhaustive std::visit
  • escrow
  • change-making
  • ordering side effects
  • authorize and capture
  • test doubles
  • requirement changes
  • How a few questions about money (“what does cancel give back?”, “what if the item gets stuck?”) decide most of a vending machine’s design.
  • Why the inserted coins are kept apart from the machine’s own coins until a sale, and why “credit” is not just a number.
  • Why paying exact change from a limited set of coins needs a search, and the case where taking the largest coin first fails.
  • How to order the steps of a sale so that a jammed item costs the customer nothing, with no undo code.
  • Why the machine’s states are a std::variant here rather than an enum with extra fields, or the State pattern, and when that would change.
  • How an exhaustive std::visit turns “a new state was added” into compile errors at every place that must decide what it means.
  • How card payment fits as one more state, and why the card is reserved before the item drops and charged only after.

This page follows the order in How to approach a case study. It assumes State and State machines and invalid-state prevention.

“Design a vending machine.”

That is the whole request. Everyone has used one, which is the danger: it is easy to start drawing classes for products, coins, and buttons before asking what the machine must get right. Most of what it must get right is about money.

Each question is here because its answer changes the design.

Question Answer (from the client) What it changes
How do customers pay? Coins. Cards “maybe next year”. Coins now; card payment is a later change, so it should not need a rewrite.
Which coins? 0.10, 0.20, 0.50, 1.00, and 2.00. No notes. The coin acceptor rejects fakes in hardware. Five coin kinds; every price is a multiple of 0.10; coin checking is outside.
Does it give change? Yes, exact change. If it cannot, it must not sell. A change-making step that can fail, and a result for “cannot give change”.
What does cancel give back? The coins the customer put in. The inserted coins are kept apart, not just added to a total.
How many items per sale? One. No basket.
What if an item gets stuck? A drop sensor sees whether an item fell. If none did, the customer must not pay. The order of the steps in a sale; a “jammed” result; the slot stops selling.
Who restocks, and how? An operator opens the service door with a key; the control panel is behind it. Nothing is sold meanwhile. A service state; operator functions only work with the door open.
Can the door open while a customer has credit? No. The operator must never be able to take a customer’s coins. An invariant on the states (INV-3).
How big? Do you need telemetry, discounts, or a phone app? One machine, up to about 60 slots, a few hundred sales a day. No telemetry, discounts, or app for now. No performance work; those features are out of scope.

Confirmed: coin sales of one item; exact change from the coins inside; cancel returning the inserted coins; jams; stocking, loading, and emptying coins with the door open.

Assumed (said aloud, written down, and open to correction; see Assumptions versus confirmed requirements):

  • One customer at a time: one keypad, one coin slot.
  • A coin the acceptor rejects never reaches the software.
  • The coin box holds as many coins as it is given. Real coin tubes fill up; see the production limitations.
  • An abandoned credit stays until someone presses cancel. No timeouts.

Out of scope: notes, telemetry, remote price changes, discounts, sales reports, and refunds after the customer has walked away.

Functional

  • FR-1 With the door open, the operator stocks each slot with a product, a price (a positive multiple of 0.10), and a count.
  • FR-2 The machine accepts 0.10, 0.20, 0.50, 1.00, and 2.00 coins and shows the credit.
  • FR-3 Choosing a slot with enough credit releases one item and pays the change.
  • FR-4 Cancel returns the coins the customer inserted, the same coins, not other coins of the same value.
  • FR-5 Change is exact and is paid from the coins in the machine, the customer’s own included. If no combination of those coins adds up to the change, the sale is refused and the credit kept.
  • FR-6 If the item does not drop, the customer is not charged, keeps their credit, and the slot is out of order until it is stocked again.
  • FR-7 The door opens only when no customer has credit. While it is open, coins are refused and nothing is sold.
  • FR-8 With the door open, the operator can load coins for change and take coins out.

Non-functional

  • NFR-1 Money is an exact whole number of cents, stored as a 64-bit integer. No floating point.
  • NFR-2 Every coin is accounted for: what is inside equals what was loaded and inserted, minus what was paid out and taken (INV-1).
  • NFR-3 The motors and the drop sensor are hardware. The logic sees them through an interface, so it can be tested without a machine.
  • NFR-4 Each action answers at once for a person at the keypad. (Not measured; the largest search is over a few dozen coins.)

Each use case has numbered acceptance criteria; the tests are named after them. See Use cases, user stories, and acceptance criteria.

UC-1 Buy with coins. The customer inserts coins and chooses a slot.

  • AC-1.1 Each accepted coin raises the credit, and the display shows it.
  • AC-1.2 With enough credit, one item drops, exact change is paid, and the coin box gains exactly the price.
  • AC-1.3 With too little credit, the price is shown and the credit is kept.
  • AC-1.4 An unknown or sold-out slot is refused, and the credit is kept.
  • AC-1.5 If exact change cannot be paid, the sale is refused; the credit, the coin box, and the stock are unchanged.
  • AC-1.6 Change may use the coins the customer has just inserted.
  • AC-1.7 Change is found even when taking the largest coin first would leave an amount no coin pays.
  • AC-1.8 A jam charges nothing and keeps the credit; the slot is out of order and is not tried again.

UC-2 Cancel.

  • AC-2.1 Cancel returns the same coins that were inserted; the credit is then zero.
  • AC-2.2 Cancel with no credit returns nothing. Choosing a slot with no credit shows its price.

UC-3 Service the machine.

  • AC-3.1 The door stays shut while there is credit.
  • AC-3.2 With the door open, coins are refused and nothing is sold.
  • AC-3.3 Stocking rejects a bad price, count, or slot, and clears a jam.
  • AC-3.4 Coins can be loaded and taken only with the door open; taking more than is inside is refused.

Each invariant names the code that keeps it. See Invariants and encapsulation.

  • INV-1 The coins inside (the coin box plus the inserted coins) equal the coins loaded and inserted, minus those paid out as change or returned by cancel, minus those taken. (VendingMachine: every function that moves coins)
  • INV-2 A coin sale adds exactly its price to the coin box. (VendingMachine::sell)
  • INV-3 The door is never open while a customer has credit. (The state type: the service state has no inserted coins; and open_door)
  • INV-4 A slot’s count falls by one only when an item drops, and is never negative. (sell, and stock)
  • INV-5 In the “has credit” state there is at least one inserted coin. (insert creates that state with one coin; every way out of it goes to another state)

The nouns in the requirements and answers: machine, slot, product, price, count, coin, credit, change, coin box, customer, operator, door, keypad, display, motor, drop sensor, item. Filtered:

  • Machine runs every use case and owns the slots and the coins. It becomes the class VendingMachine.
  • Coin is one of five fixed values. It becomes the enum Coin.
  • Credit, change, and coin box are all “some coins of each kind”. One value type, Coins, serves all three. Credit is not a separate number: it is the total of the inserted coins.
  • Slot holds a product name, a price, a count, and whether it is jammed. That is data with no behaviour of its own, so it becomes a plain struct, Slot, owned by the machine.
  • Product is only a name on a slot here. No class.
  • Door open or shut, and credit present or not, decide what every button means. They become the machine’s state.
  • Motor and drop sensor are hardware. Together they become one interface, Dispenser: “turn this slot’s motor; did an item fall?”
  • Customer, operator, keypad, and display are outside. They are the callers of the machine’s functions; the display shows the string display() returns.
Entity sketch of the vending machine (step 1). Solid arrows: owns, holds, or is one of. Dashed arrow: uses without owning
Text description of the diagram

Nine boxes. Solid arrows mean “owns”, “holds”, or “is one of”; the dashed arrow means “uses without owning”. VendingMachine owns one or more Slot objects, keyed by code, and owns a Coins value, the coin box. VendingMachine holds exactly one State. A State is one of Idle, HasCredit, or Maintenance. HasCredit owns a second Coins value, the inserted coins. VendingMachine uses a Dispenser but does not own it.

Diagram source (Mermaid)
flowchart LR
VM[VendingMachine] -->|"owns 1..* slots, by code"| Slot
VM -->|owns the coin box| Box[Coins]
VM -->|holds exactly one| State
State -->|is one of| Idle
State -->|is one of| HasCredit
State -->|is one of| Maintenance
HasCredit -->|owns the inserted coins| Escrow[Coins]
VM -.->|uses, not owned| Dispenser

The inserted coins are inside the HasCredit state, not beside it. That placement is the main decision in this design, and the class design explains why.

The design below is step 1 of the example, the complete answer to FR-1 … FR-8. Card payment is added in When the requirements change.

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

coins.hpp
// The coins the machine accepts, smallest first (FR-2). The names say the
// value in cents: c10 is 0.10, c200 is 2.00. `enum class` keeps the names
// inside the type (Coin::c10) and stops a Coin from being used as an int by
// accident. The order matters: each enumerator's underlying number (c10 is
// 0, c20 is 1, ... c200 is 4) is used below as an index into an array.
enum class Coin { c10, c20, c50, c100, c200 };
// Every coin, smallest first, so code can loop over all five kinds with
// `for (const Coin coin : all_coins)`. `inline constexpr` makes it one
// constant, fixed at compile time and shared by every file that includes
// this header.
inline constexpr std::array<Coin, 5> all_coins{Coin::c10, Coin::c20, Coin::c50, Coin::c100,
Coin::c200};
// The value of one coin in whole cents. Money is kept in integer cents
// (std::int64_t, a 64-bit integer), never in a double, so 0.10 + 0.20 is
// exactly 30 and never 0.30000000000000004. constexpr allows the answer to
// be worked out at compile time when the coin is known.
constexpr std::int64_t value_cents(Coin coin) {
switch (coin) {
case Coin::c10:
return 10;
case Coin::c20:
return 20;
case Coin::c50:
return 50;
case Coin::c100:
return 100;
case Coin::c200:
return 200;
}
// Every Coin returned above. This line exists because the compiler
// cannot be sure a Coin holds one of the five names (a cast could put
// any number in it), and a function must not run off its end.
return 0; // not reached for a valid Coin
}

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

coins.hpp
// A handful of coins: how many of each kind. A value type, so the
// customer's coins, the change, and the coin box are all the same type.
// It is five counts and nothing else: copying a Coins copies the counts,
// and two Coins are equal when every count is equal. A count never goes
// below zero: add refuses a negative number and remove refuses to take
// coins that are not there.
class Coins {
public:
// `= default`: a new Coins is empty, every count 0 (see counts_ below).
Coins() = default;
// Adds n coins of one kind; `int n = 1` means add(coin) adds one coin.
// Throws std::invalid_argument if n is negative.
void add(Coin coin, int n = 1);
// Adds every coin in other, kind by kind: pour one handful into another.
void add(const Coins& other);
// Takes every coin in other out of these coins. It checks first, so a
// refused remove changes nothing.
// Throws std::logic_error if these coins do not contain other.
void remove(const Coins& other);
int count(Coin coin) const { return counts_[index(coin)]; }
// The value of all the coins together, in cents.
std::int64_t total_cents() const;
bool empty() const { return total_cents() == 0; }
// True if, for every kind, there are at least as many here as in
// other: "could other be taken out of these coins?"
bool contains(const Coins& other) const;
// `= default` asks the compiler to write ==: two Coins are equal when
// their counts_ arrays are equal. `friend` lets this free function read
// the private counts_. Tests use it to compare whole handfuls at once.
friend bool operator==(const Coins&, const Coins&) = default;
private:
// The position of a coin's count in counts_: its enumerator's number
// (c10 is 0, ... c200 is 4). static_cast turns the enum into that
// number on purpose, since an enum class does not convert by itself.
static std::size_t index(Coin coin) { return static_cast<std::size_t>(coin); }
// One count per kind of coin. The `{}` starts every count at 0.
std::array<int, all_coins.size()> counts_{};
};

Coins is a value object: five counts in a std::array, copied freely, compared with a defaulted ==. Because the inserted coins, the change, and the coin box are the same type, “add the customer’s coins to the box” and “does the box contain this change?” are one function call each, and a test can compare two handfuls of coins directly.

make_change is a free function. It needs an amount and some coins, and nothing else about the machine, so it can be tested on its own with any coins.

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

machine.hpp
// Each state holds only the data that exists in it. The inserted coins
// exist only while there is credit, so only HasCredit has them.
// Idle: door shut, no coins inserted, waiting for a customer.
struct Idle {};
// HasCredit: a customer has inserted coins and not yet bought or cancelled.
// "Escrow" means money held aside for someone until a deal completes: these
// coins are not in the coin box yet, so cancel can hand back these exact coins.
struct HasCredit {
Coins escrow; // the customer's own coins, never empty in this state
};
struct Maintenance {}; // the door is open
// std::variant<Idle, HasCredit, Maintenance> holds exactly one of the three
// at any moment, and knows which one. Moving to another state means
// assigning a different alternative, which destroys the old one with its
// data: leaving HasCredit throws away its escrow. So "the door is open and
// a customer has coins inside" cannot even be written down.
using State = std::variant<Idle, HasCredit, Maintenance>;

There are three states. The data each one needs is inside it, and only there: the inserted coins exist in HasCredit and in no other state. The architecture section compares this with the alternatives.

struct Slot

plain data, owned by the machine

Data members

  • std::string product;
  • std::int64_t price_cents;
  • int count;
  • bool jammed; out of order until stocked again

class Coins

value type: how many of each coin

Data members

  • std::array<int, 5> counts_;

Member functions

  • void add(Coin coin, int n);
  • void remove(const Coins& other); throws std::logic_error if not contained
  • std::int64_t total_cents() const;
  • bool contains(const Coins& other) const;

class VendingMachine

the orchestrator; one customer at a time

Data members

  • State state_; Idle, HasCredit, or Maintenance; starts in Maintenance
  • std::map<std::string, Slot> slots_; owned; keyed by code, such as A1
  • Coins box_; owned; the machine's coins
  • Dispenser& dispenser_; not owned; must outlive the machine

Member functions

  • bool insert(Coin coin);
  • SaleResult choose(const std::string& slot);
  • Coins cancel();
  • bool open_door();
  • void close_door();
  • void stock(const std::string& slot, std::string product, std::int64_t price_cents, int count);
  • void load_coins(const Coins& coins);
  • Coins take_coins(const Coins& coins);
  • std::string display() const;
The value types and the machine in step 1, with the owner of each member

The results of a sale are values:

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

machine.hpp
// Every answer choose can give. Expected outcomes (not enough credit, sold
// out) are values the caller shows on the display, not exceptions: a
// customer pressing the wrong button is normal, not a bug.
enum class SaleStatus {
sold,
no_credit, // a slot was chosen before any coin
not_enough_credit, // price_cents says how much the item costs
unknown_slot,
sold_out,
out_of_order, // the slot jammed earlier
no_change, // the machine cannot pay the change exactly
jammed, // the item did not drop; nothing was charged
unavailable, // the door is open
};
// What choose returns: the status, plus the change and price when they
// mean something. Plain data, returned by value.
struct SaleResult {
SaleStatus status;
Coins change; // coins to the tray when sold
std::int64_t price_cents = 0; // the slot's price, when known
};

And the hardware is an interface the machine is given:

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

dispenser.hpp
// The machine's only view of the motors: an interface, a class that says
// what can be asked (release) and leaves how to its derived classes. A real
// machine would be given a class that drives the hardware; the demo and the
// tests give it a stand-in that pretends. The machine holds a Dispenser&
// and never knows which one it got.
class Dispenser {
public:
// A virtual destructor, so that deleting a stand-in through a
// Dispenser pointer runs the stand-in's own destructor too.
virtual ~Dispenser() = default;
// `= 0` makes release pure virtual: Dispenser has no body for it, and
// every class derived from it must provide one before it can be
// created (the stand-ins mark theirs `override`).
// Turns the slot's motor once. True if the drop sensor saw an item
// fall; false if the item jammed and nothing reached the tray.
virtual bool release(const std::string& slot) = 0;
};
Rule Where Why there
A price is a positive multiple of 0.10 (FR-1) VendingMachine::stock The only way a price gets in. Any other price could never be paid exactly.
Change is exact, from the coins given (FR-5) make_change, a free function It needs nothing but coins and an amount, so it is tested alone.
Cancel returns the same coins (FR-4) HasCredit::escrow The inserted coins are kept apart until a sale, so there is nothing to work out.
A jam costs nothing (FR-6) VendingMachine::sell, by the order of steps The motor runs before any coin moves; see the sale.
The door stays shut with credit (FR-7, INV-3) open_door, and the State type Maintenance has no inserted coins, so “open with credit” cannot be represented.
A jammed slot stops selling (FR-6) Slot::jammed, set in sell, reset in stock The slot’s own data; only restocking (with the door open) clears it.

Expected outcomes are values; mistakes are exceptions

Section titled “Expected outcomes are values; mistakes are exceptions”

“Not enough credit”, “sold out”, “cannot give change”, and “jammed” are normal events at a vending machine; the display must say something for each. They come back as a SaleStatus in a SaleResult, and a refused coin as false from insert. Exceptions are kept for mistakes in the code that calls the machine: stocking with the door shut (the control panel is behind the door, so that call means a bug), a price that is not a multiple of 0.10, taking coins that are not there. A Dispenser that throws, say because the motor controller stopped answering, is not caught: the exception reaches the caller, and the machine is left as it was. See Errors and contracts.

Before writing the functions, trace one use case through the outline. The machine holds two 2.00 and two 0.50 coins in the box; the slot A1 has one water at 1.00; the motor will jam.

  1. insert(0.50): the state is Idle, so it becomes HasCredit with one 0.50. Display “CREDIT 0.50”.
  2. insert(0.50): HasCredit gains a second 0.50. Credit 1.00.
  3. choose("A1"): the state is HasCredit, so sell runs. The slot exists, is not jammed, and has one item; 1.00 covers 1.00. Change of 0 is found (no coins). dispenser_.release("A1") returns false.
  4. sell marks A1 jammed and returns the same HasCredit. Nothing else changed: box still two 2.00 and two 0.50, count still 1, credit 1.00.
  5. choose("A1") again: out of order. The motor is not tried again.
  6. cancel(): returns the two 0.50 coins from HasCredit; state Idle.

Each step uses only the members in the outline, plus the private helper sell, so the outline is complete for this use case. The demo below runs this trace.

States: an enum, the State pattern, or a variant?

Section titled “States: an enum, the State pattern, or a variant?”

The machine behaves differently in each state: a coin is credit when idle, more credit with credit, and refused with the door open. Some representation of “which state are we in” is needed. Three are common.

A fourth design is also reasonable: drop Idle and treat “has credit with no coins” as idle, leaving two states. It is smaller, but the empty case then needs checks in cancel, open_door, and the display, and INV-5 becomes a convention. Three states keep those checks out.

The obvious way to pay 0.60 is to take the largest coin that fits, then the next, and so on. With an unlimited supply of each coin, that works for these five coins. A machine does not have an unlimited supply.

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

coins.cpp
// namespace { ... } with no name keeps search private to this file: only
// make_change, below, can call it.
namespace {
// Tries coins from all_coins[index] down to the smallest, taking as many
// of the larger coin as possible first and backing off one at a time.
// `below[i]` is the value of every available coin smaller than
// all_coins[i]; a branch that cannot reach `remaining` stops at once.
//
// In: remaining, the cents still to pay; index, the position in all_coins
// of the largest coin still allowed (4 is 2.00, 0 is 0.10, -1 means
// none left); available, the coins that may be used; below, the
// table described above; chosen, the coins picked so far.
// Out: true if remaining can be paid exactly, and then chosen has been
// updated to include the coins that pay it; false if it cannot, and
// then chosen is untouched (every try works on a copy).
// Each level of the recursion decides one kind of coin, largest first, so
// it is at most six calls deep: one per kind, plus one that finds
// remaining == 0 or has no kinds left.
bool search(std::int64_t remaining, int index, const Coins& available,
const std::array<std::int64_t, all_coins.size() + 1>& below, Coins& chosen) {
if (remaining == 0) return true; // paid exactly: nothing more to add
if (index < 0) return false; // money still owed, but no kinds of coin left
// The index as the unsigned type that std::array indexing expects.
const auto i = static_cast<std::size_t>(index);
// The early stop: below[i] plus all the coins of this kind is every
// coin still allowed. If even all of them together are worth less than
// remaining, no choice from here can work, so do not try any.
if (remaining > below[i] + available.count(all_coins[i]) * value_cents(all_coins[i])) {
return false;
}
const Coin coin = all_coins[i];
// The most coins of this kind worth trying: no more than there are,
// and no more than fit in remaining (integer division rounds down).
// The <std::int64_t> picks the type, because count is an int and the
// division gives an int64_t, and std::min needs both the same.
const std::int64_t most = std::min<std::int64_t>(available.count(coin),
remaining / value_cents(coin));
// Back off one coin at a time: try `most` of this coin, then one fewer,
// down to none. For each, ask the smaller coins to pay the rest.
for (std::int64_t n = most; n >= 0; --n) {
// A copy, so a failed try leaves chosen exactly as it was.
Coins attempt = chosen;
attempt.add(coin, static_cast<int>(n)); // n <= a count, so it fits in an int
if (search(remaining - n * value_cents(coin), index - 1, available, below, attempt)) {
// The smaller coins paid the rest (and added themselves to
// attempt), so attempt is a full answer: keep it and stop.
chosen = attempt;
return true;
}
}
return false; // no number of this coin, 0 included, led to an answer
}
} // namespace
// The entry point. Returns the change for amount_cents taken from
// available, or std::nullopt ("no value") if no combination of those coins
// adds up to it exactly. available is only read, never changed: the caller
// takes the change out of its coins itself, once it has decided to sell.
// Throws std::invalid_argument for a negative amount. Zero is fine, and
// gives an empty Coins.
std::optional<Coins> make_change(std::int64_t amount_cents, const Coins& available) {
if (amount_cents < 0) throw std::invalid_argument("change cannot be negative");
// Build the table for the early stop. below[0] is 0 (nothing is
// smaller than 0.10), and each next entry adds the value of all the
// available coins of one more kind, so below[5] is the value of
// everything. The `{}` starts every entry at 0.
std::array<std::int64_t, all_coins.size() + 1> below{};
for (std::size_t i = 1; i <= all_coins.size(); ++i) {
below[i] = below[i - 1] + available.count(all_coins[i - 1]) * value_cents(all_coins[i - 1]);
}
Coins chosen; // starts empty; search fills it in only on success
// Start from the largest coin, 2.00, at the last position, 4.
const int largest = static_cast<int>(all_coins.size()) - 1;
if (!search(amount_cents, largest, available, below, chosen)) return std::nullopt;
return chosen; // wrapped into a std::optional that holds a value
}
How this code works: make_change and search

make_change does two things: it builds a small table, below, and then asks search for an answer, starting at the largest coin.

  1. The table. below[i] is the value of all the available coins smaller than all_coins[i]. It is built from the smallest coin up: each entry is the one before plus the value of one more kind of coin.
  2. One call of search handles one kind of coin. It is given the amount still owed (remaining) and the position of the coin to decide on (index). It decides how many of that coin to use, and leaves the rest to a call for the next smaller coin (index - 1).
  3. Two ways to stop. If remaining is 0, the amount has been paid exactly: success. If index is below 0, there are no kinds of coin left but money is still owed: failure.
  4. The early stop. below[i] plus all the coins of this kind is everything this call and the calls below it may use. If that is less than remaining, no choice can work, so the call fails at once without trying anything.
  5. Back off one at a time. most is the largest number of this coin that is available and fits. The loop tries most, then one fewer, down to none. For each number it works on a copy, attempt, and asks the smaller coins to pay the rest. The first try that succeeds is kept (chosen = attempt) and the call returns true. Because larger numbers of larger coins are tried first, the first answer found is the one that prefers large coins.
  6. How the answer gets back. Each call passes its own attempt to the next call, where it is called chosen. When a call succeeds, it copies its attempt into its chosen, which is the attempt of the call above. That call then succeeds too and does the same, level by level, until the top call fills the chosen in make_change. A call that fails copies nothing, so its chosen is left as it was.

A worked example: 0.60 from one 0.50 and three 0.20 (AC-1.7). The table is below[0] = 0, below[1] = 0 (no 0.10 coins), below[2] = 60 (three 0.20), below[3] = 110, below[4] = 110, below[5] = 110.

Call: coin, remaining Early stop? most What happens
2.00, 60 60 > 110 + 0? no 0 (none available) try 0, go on to 1.00
1.00, 60 60 > 110 + 0? no 0 (none available) try 0, go on to 0.50
0.50, 60 60 > 60 + 50? no 1 try one 0.50, leaving 10 for 0.20
0.20, 10 10 > 0 + 60? no 0 (10 / 20 is 0) try 0, go on to 0.10
0.10, 10 10 > 0 + 0? yes (not reached) fail: back to 0.50
0.50, 60 try zero 0.50, leaving 60 for 0.20
0.20, 60 60 > 0 + 60? no 3 try three 0.20, leaving 0
0.10, 0 remaining is 0: success

The answer is three 0.20. Largest-first without backing off would have stopped at the fifth row and said “no change”.

In the worst case the search tries every combination of counts: the product of (count + 1) over the five coin kinds. That grows with the number of coins in the box, but it is bounded, and the early stop cuts most branches. It was not measured. A table-based method (dynamic programming over amounts in steps of 0.10) takes time proportional to the number of kinds times the amount. It could replace the search without changing any caller only if it kept the preference for large coins, which a test (change_prefers_larger_coins_when_both_work) and the last line of the demo depend on.

A sale has four parts: check the slot and the credit, find the change, drop the item, move the money. The order matters.

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

machine.cpp
// Tries to sell the item in slot `code` to a customer whose inserted coins
// are `escrow`. Called by choose only in the HasCredit state.
// In: the slot code, the inserted coins (read only), and result, which
// sell fills in (status, price, change) for choose to return.
// Out: the next state. Idle after a sale; otherwise HasCredit with the same
// coins, so a refused sale keeps the customer's credit.
// The order is "check, plan, drop, commit": every check and the change
// plan come first and change nothing; then the motor, the only step that
// can fail; then the money moves, in steps that cannot fail.
State VendingMachine::sell(const std::string& code, const Coins& escrow, SaleResult& result) {
// The state to return on every refusal: the same credit as before.
const HasCredit unchanged{escrow};
// A pointer into slots_, or nullptr if there is no slot with that code.
// A pointer rather than a copy, because a sale or a jam changes the slot.
Slot* slot = find(code);
if (slot == nullptr) {
result.status = SaleStatus::unknown_slot;
return unchanged;
}
result.price_cents = slot->price_cents; // known from here on, even if refused
if (slot->jammed) {
result.status = SaleStatus::out_of_order;
return unchanged;
}
if (slot->count == 0) {
result.status = SaleStatus::sold_out;
return unchanged;
}
const std::int64_t credit = escrow.total_cents(); // e.g. 200 for one 2.00 coin
if (credit < slot->price_cents) {
result.status = SaleStatus::not_enough_credit;
return unchanged;
}
// Plan the change from every coin the machine would hold after the
// sale, the customer's included. Nothing has changed yet.
// pool is a copy: box_ itself is not touched until the commit below.
Coins pool = box_;
pool.add(escrow);
// The change owed is the credit minus the price, 0 for exact money.
// make_change gives an empty optional if those coins cannot pay it.
const std::optional<Coins> change = make_change(credit - slot->price_cents, pool);
if (!change) { // an empty optional converts to false
result.status = SaleStatus::no_change;
return unchanged;
}
// The one step that can fail is the motor, so it comes before any
// money moves. A jam leaves the coins where they were.
if (!dispenser_.release(code)) {
// Jammed. The one thing that changes is the slot's flag, so nobody
// else pays for the stuck item; the count stays, since the item is
// still in the slot.
slot->jammed = true;
result.status = SaleStatus::jammed;
return unchanged;
}
// From here nothing can fail: the change was found in pool.
--slot->count; // one item fewer in the slot
// *change reads the Coins inside the optional (it is known to hold one).
// remove cannot throw: pool contains the change, because make_change
// chose it from pool.
pool.remove(*change);
// The box is now its old coins plus the customer's, minus the change:
// it has gained exactly the price (INV-2).
box_ = pool;
result.status = SaleStatus::sold;
result.change = *change; // the coins that drop into the tray
// Idle: the customer's coins are now in box_, so the HasCredit state and
// its escrow are gone.
return Idle{};
}
How this code works: VendingMachine::sell

sell runs only while there is credit. It returns the next state, and writes the details into result for choose to hand back.

  1. Checks. Each if refuses the sale and returns unchanged, a HasCredit with the very same coins, so the customer keeps their credit. The order: no such slot, the slot is jammed, the slot is empty, not enough credit. The price goes into result as soon as the slot is known, so even a refusal can show it.
  2. Plan the change. pool is a copy of the coin box with the customer’s coins added. make_change looks for the change in it. If there is none, the sale is refused, and because only the copy was touched, nothing has changed.
  3. Drop the item. dispenser_.release(code) is the only step that can fail. On a jam, the slot is marked jammed and the credit is kept. No coin had moved, so there is nothing to undo.
  4. Commit. The item is in the tray. The count goes down by one, the change comes out of pool, and pool becomes the new coin box. These steps cannot fail: the change was found in pool, so remove always has the coins. The state becomes Idle, which drops the escrow: those coins are now part of box_.

With the first sale of the demo: the box holds one 0.50 and three 0.20, the customer inserted one 2.00, and B1 costs 1.40.

Step Values
Checks B1 exists, not jammed, count 3; credit 200 is not less than 140
Plan pool is 1 x 2.00 + 1 x 0.50 + 3 x 0.20; owed 200 - 140 = 60; change is 3 x 0.20
Drop the stand-in reports an item fell
Commit B1’s count becomes 2; box_ becomes 1 x 2.00 + 1 x 0.50, which is 140 more than before
  • No Product class. A product is a name on a slot. If products gained barcodes, allergens, or prices shared across slots, a product type would earn its place.
  • No Inventory class. The slots are a std::map inside the machine, and the only rules about them (price, count, jam) are a few lines each. A separate class would mostly forward calls.
  • No Singleton. There is one machine, but nothing gains from making it global; the demo and every test build their own. See When patterns hurt.
  • No Observer for the display. The display reads display() after each action. With one display and one caller, there is nothing to notify.
  • No class per coin. Coins differ only by value, a row in a switch.

The example is built in two steps. Each is a complete program with its own tests:

  • step-1: the coin machine, FR-1 … FR-8.
  • step-2: card payment, the change.

Step 1: the whole coin machine (FR-1 … FR-8)

Section titled “Step 1: the whole coin machine (FR-1 … FR-8)”

Start with the state type, because every function depends on it. The tempting first version is an enum with fields beside it:

Flawed (intentional)Demonstrates a mistake on purpose. Do not copy it; see the corrected version.

// The state is only a name; the data that belongs to a state sits beside it.
enum class Mode { idle, has_credit, maintenance };
class VendingMachine {
public:
// Where it goes wrong: this switches to maintenance in every mode. In
// has_credit the customer's coins are still in escrow_, so the door
// opens with them inside (INV-3 broken). Nothing in the types stops it:
// the rule lives only in the programmer's memory.
bool open_door() {
mode_ = Mode::maintenance; // forgot: refuse if escrow_ is not empty
return true;
}
// ...
private:
Mode mode_ = Mode::maintenance;
// Two fields that must agree, and nothing makes them: every function
// that changes mode_ must also remember to fill or empty escrow_.
Coins escrow_; // meaningful only when mode_ == Mode::has_credit
};

The compiler accepts this, and the door opens with a customer’s coins inside. Every function that changes mode_ must also remember escrow_. The corrected version puts the coins inside the state that has them, so a Maintenance state with coins cannot be written down:

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

machine.hpp
// Each state holds only the data that exists in it. The inserted coins
// exist only while there is credit, so only HasCredit has them.
// Idle: door shut, no coins inserted, waiting for a customer.
struct Idle {};
// HasCredit: a customer has inserted coins and not yet bought or cancelled.
// "Escrow" means money held aside for someone until a deal completes: these
// coins are not in the coin box yet, so cancel can hand back these exact coins.
struct HasCredit {
Coins escrow; // the customer's own coins, never empty in this state
};
struct Maintenance {}; // the door is open
// std::variant<Idle, HasCredit, Maintenance> holds exactly one of the three
// at any moment, and knows which one. Moving to another state means
// assigning a different alternative, which destroys the old one with its
// data: leaving HasCredit throws away its escrow. So "the door is open and
// a customer has coins inside" cannot even be written down.
using State = std::variant<Idle, HasCredit, Maintenance>;

Every customer action is then a visit. The visitor reads the current state and returns the next one; state_ is assigned only after the visit has finished:

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

machine.cpp
// Every customer action is a visit over the state, so each state must
// say what the action means in it. The visitor reads the current state
// and returns the next one; state_ is assigned only after the visit has
// finished, so no visitor replaces the object it is reading.
//
// How the pieces fit: std::visit(visitor, state_) looks at which
// alternative state_ holds right now and calls the visitor with it. Here
// the visitor is an Overloaded{...}: a small helper defined at the top of
// this file that bundles several lambdas into one object, so std::visit
// calls the lambda whose parameter type matches (Idle, HasCredit, or
// Maintenance). If a state had no lambda, the call would not compile.
// Each lambda returns the next State, and that return value is what gets
// assigned to state_.
//
// insert: a coin dropped into the slot. Returns true if it is kept as
// credit, false if it is refused (it falls back to the tray).
bool VendingMachine::insert(Coin coin) {
bool accepted = true; // the lambdas below set it to false to refuse
state_ = std::visit(Overloaded{
// [&] lets a lambda use coin and accepted from
// this function, by reference.
[&](const Idle&) -> State {
// The first coin: start a new credit with it.
Coins escrow;
escrow.add(coin);
return HasCredit{escrow};
},
[&](const HasCredit& now) -> State {
// More credit: a copy of the current state
// with one more coin. now is not changed.
HasCredit next = now;
next.escrow.add(coin);
return next;
},
[&](const Maintenance&) -> State {
accepted = false; // the door is open: refuse it
return Maintenance{}; // and stay in Maintenance
},
},
state_);
return accepted;
}
How this code works: VendingMachine::insert, a visit

The helper Overloaded. It is defined at the top of machine.cpp (not shown): template <typename... F> struct Overloaded : F..., whose body is one line, using F::operator()...;, plus a deduction guide. typename... F means “any number of types”. Each lambda is an object of its own unnamed class with a call operator, operator(). Overloaded{a, b, c} makes one object whose class inherits from all three lambda classes, and the using line brings their three call operators together as one overloaded set. Calling it with an Idle picks the lambda that takes an Idle, just as an ordinary overloaded function would. The deduction guide lets the compiler work out the lambda types from the braces.

What std::visit does. std::visit(f, state_) checks which alternative state_ holds and calls f with a reference to it. So exactly one of the three lambdas runs.

The three answers.

  • Idle: the first coin. A new Coins with this one coin becomes a HasCredit.
  • HasCredit: another coin. A copy of the current state with the coin added is returned; now itself is not changed.
  • Maintenance: the door is open. accepted is set to false, which the lambda can do because [&] captures the function’s local variables by reference, and the state stays Maintenance.

Whichever lambda ran, its return value is a State, and state_ = std::visit(...) stores it once the visit is over.

The demo’s first coins. The machine is Idle and 2.00 is inserted: the Idle lambda runs and state_ becomes HasCredit holding one 2.00, so the display reads CREDIT 2.00. Later, with the door open, 1.00 is inserted: the Maintenance lambda runs, insert returns false, and the demo prints refused.

Why not assign state_ inside the lambda? The lambda’s parameter is a reference into state_. A variant keeps its value inside itself, so nothing is freed, but assigning a different alternative destroys the object that reference names, and any use of it afterwards is undefined behaviour. Assigning the same alternative changes it in place, so the reference quietly sees the new value. Here each branch returns a value instead, and state_ is assigned once the visit is over, so no reference outlives its object. The cost is copying a HasCredit (five integers) when it does not change, which is nothing next to a coin dropping.

The same reasoning covers sell, which choose calls with now.escrow, a reference into state_. sell changes the slots and the coin box, never state_, so the reference stays valid until the visit returns.

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

machine.cpp
// choose: the customer pressed a slot button, such as "B1". Returns what
// happened as a SaleResult. Like insert, it is one visit: each state says
// what pressing a button means in it, and returns the next state.
SaleResult VendingMachine::choose(const std::string& code) {
// Start with "no credit, no change, price 0"; the lambdas fill in the
// parts that apply. The `{}` in the middle is an empty Coins.
SaleResult result{SaleStatus::no_credit, {}, 0};
state_ = std::visit(Overloaded{
[&](const Idle&) -> State {
// No coins yet: the status stays no_credit,
// and the price is filled in when the slot
// exists, so the display can show it. find
// gives nullptr for an unknown code, and the
// `if (... s = find(code))` runs only when it
// found one.
if (const Slot* s = find(code)) result.price_cents = s->price_cents;
return Idle{};
},
[&](const HasCredit& now) -> State {
// There is credit: try to sell. sell fills in
// result and returns the next state. now.escrow
// is a reference into state_, still valid
// because sell never assigns to state_.
return sell(code, now.escrow, result);
},
[&](const Maintenance&) -> State {
result.status = SaleStatus::unavailable;
return Maintenance{};
},
},
state_);
return result;
}

Cancel returns the coins held in HasCredit, not coins of the same value worked out from the box:

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

machine.cpp
// The customer pressed cancel. Returns the coins that go back to the tray:
// with credit, exactly the coins they inserted; otherwise none. It never
// throws and never fails; in Idle and Maintenance it changes nothing.
Coins VendingMachine::cancel() {
Coins returned; // empty unless the HasCredit branch fills it
state_ = std::visit(Overloaded{
// [] captures nothing: these two lambdas need
// nothing from the function, they only return.
[](const Idle&) -> State { return Idle{}; },
[&](const HasCredit& now) -> State {
returned = now.escrow; // the same coins, not their value
// A copy was taken just above, so replacing
// HasCredit (and its escrow) loses nothing.
return Idle{};
},
[](const Maintenance&) -> State { return Maintenance{}; },
},
state_);
return returned;
}

The door is a state change that can be refused:

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

machine.cpp
// The operator tries to open the door. Returns true if it is now open (or
// was already), false if it stays shut because a customer has credit.
bool VendingMachine::open_door() {
bool opened = true;
state_ = std::visit(Overloaded{
[](const Idle&) -> State { return Maintenance{}; },
[&](const HasCredit& now) -> State {
opened = false; // INV-3: never open with a customer's coins inside
return now; // a copy of the current state: nothing changes
},
[](const Maintenance&) -> State { return Maintenance{}; },
},
state_);
return opened;
}
// Closing is not a visit: it means one thing, and only in Maintenance.
// Closing a door that is not open is a bug in the caller, so it throws
// std::logic_error (require_door_open checks with
// std::holds_alternative<Maintenance>). Otherwise the machine is Idle.
void VendingMachine::close_door() {
require_door_open("closing the door");
state_ = Idle{};
}

stock, load_coins, and take_coins check that the door is open with std::holds_alternative<Maintenance> and throw std::logic_error otherwise. They are not visits: they mean the same thing in every state that is not Maintenance (a bug in the caller).

The states of the machine in step 1 and the calls that move it between them
Text description of the diagram

Three states. A new machine starts in Maintenance with the door open. close_door moves it to Idle. In Idle, inserting a coin moves it to HasCredit. In HasCredit, inserting another coin, or a sale that is refused (not enough credit, sold out, no change, jammed), keeps it in HasCredit. A sale in which the item drops moves it to Idle, and so does cancel, which returns the coins. In Idle, open_door moves it to Maintenance. In HasCredit, open_door is refused and the state stays HasCredit. In Maintenance, coins are refused and nothing is sold.

Diagram source (Mermaid)
stateDiagram-v2
[*] --> Maintenance : installed, door open
Maintenance --> Idle : close_door
Idle --> HasCredit : insert coin
HasCredit --> HasCredit : insert coin, or a sale refused
HasCredit --> Idle : choose [item dropped, change paid]
HasCredit --> Idle : cancel [coins returned]
Idle --> Maintenance : open_door
HasCredit --> HasCredit : open_door [refused]
The first sale in the step 1 demo: 2.00 for crisps at 1.40
Text description of the diagram

The customer inserts 2.00 and the machine shows CREDIT 2.00. The customer chooses B1. The machine checks that B1 is in stock and that the credit of 2.00 covers the price of 1.40, so 0.60 is owed. It asks make_change for 0.60 from the coin box plus the inserted coins, and gets three 0.20 coins. It asks the Dispenser to release B1, and the Dispenser reports that an item dropped. Only then does the machine reduce B1’s count by one, put the 2.00 in the box, and take the three 0.20 coins out of it. It returns “sold” with the change.

Diagram source (Mermaid)
sequenceDiagram
participant C as customer
participant M as VendingMachine
participant MC as make_change
participant D as Dispenser
C->>M: insert(2.00)
M-->>C: CREDIT 2.00
C->>M: choose(B1)
M->>M: B1 in stock, 1.40, credit 2.00, owe 0.60
M->>MC: make_change(60, box plus inserted coins)
MC-->>M: 3 x 0.20
M->>D: release(B1)
D-->>M: true, an item dropped
M->>M: count down by one, box takes 2.00, pays 3 x 0.20
M-->>C: sold, change 3 x 0.20

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

main.cpp
// insert, choose, cancel, and box are small helpers above main (not shown)
// that call the machine and print one line each: what was done, the result,
// and the display. DemoDispenser is a stand-in for the motors that reports
// "dropped" for every slot except those in its `jams` set.
int main() {
// motors is created first, so it outlives m (locals are destroyed in
// reverse order). The machine keeps only a reference to it.
DemoDispenser motors;
// A new machine has three empty slots and starts with the door open
// (Maintenance), so the operator can stock it.
VendingMachine m({"A1", "A2", "B1"}, motors);
// stock(slot, product, price in cents, count): water costs 1.00.
m.stock("A1", "Water", 100, 2);
m.stock("A2", "Juice", 150, 1);
m.stock("B1", "Crisps", 140, 3);
// A "float" is the coins put in a till at the start so change can be
// paid: here one 0.50 and three 0.20.
Coins float_coins;
float_coins.add(Coin::c50, 1);
float_coins.add(Coin::c20, 3);
m.load_coins(float_coins);
m.close_door(); // Maintenance to Idle: customers can now buy
std::cout << "Display: " << m.display() << '\n';
box(m);
std::cout << "-- 0.60 change from 1 x 0.50 + 3 x 0.20\n";
insert(m, Coin::c200);
choose(m, "B1");
box(m);
std::cout << "-- short credit, then the last juice\n";
insert(m, Coin::c100);
choose(m, "A2");
insert(m, Coin::c50);
choose(m, "A2");
std::cout << "-- changed their mind\n";
insert(m, Coin::c50);
insert(m, Coin::c20);
cancel(m);
std::cout << "-- no coins for 0.60 now\n";
box(m);
insert(m, Coin::c200);
choose(m, "B1");
std::cout << "Operator opens door -> " << (m.open_door() ? "open" : "refused, credit pending")
<< '\n';
choose(m, "A1");
std::cout << "-- a jam\n";
motors.jams.insert("A1"); // from now on the stand-in reports A1 as jammed
insert(m, Coin::c50);
insert(m, Coin::c50);
choose(m, "A1");
choose(m, "A1");
choose(m, "A2");
cancel(m);
std::cout << "-- the operator's visit\n";
motors.jams.clear(); // the operator frees the stuck item
std::cout << "Operator opens door -> " << (m.open_door() ? "open" : "refused") << " | "
<< m.display() << '\n';
insert(m, Coin::c100); // refused: the door is open
m.stock("A1", "Water", 100, 6); // restocking also clears A1's jam flag
m.stock("A2", "Juice", 150, 4);
// The operator empties the 2.00 coins and adds small ones for change.
Coins takings;
takings.add(Coin::c200, 2);
std::cout << "Takes " << vending::describe(m.take_coins(takings)) << '\n';
Coins small;
small.add(Coin::c20, 5);
small.add(Coin::c10, 5);
m.load_coins(small);
m.close_door();
box(m);
insert(m, Coin::c200);
choose(m, "B1");
}
Expected output
Display: INSERT COINS
coin box: 1 x 0.50 + 3 x 0.20
-- 0.60 change from 1 x 0.50 + 3 x 0.20
Insert 2.00 -> CREDIT 2.00
Choose B1 (1.40) -> sold: Crisps, change 3 x 0.20 | INSERT COINS
coin box: 1 x 2.00 + 1 x 0.50
-- short credit, then the last juice
Insert 1.00 -> CREDIT 1.00
Choose A2 (1.50) -> not enough credit | CREDIT 1.00
Insert 0.50 -> CREDIT 1.50
Choose A2 (1.50) -> sold: Juice, change none | INSERT COINS
-- changed their mind
Insert 0.50 -> CREDIT 0.50
Insert 0.20 -> CREDIT 0.70
Cancel -> returns 1 x 0.50 + 1 x 0.20 | INSERT COINS
-- no coins for 0.60 now
coin box: 1 x 2.00 + 1 x 1.00 + 2 x 0.50
Insert 2.00 -> CREDIT 2.00
Choose B1 (1.40) -> cannot give change, choose another or cancel | CREDIT 2.00
Operator opens door -> refused, credit pending
Choose A1 (1.00) -> sold: Water, change 1 x 1.00 | INSERT COINS
-- a jam
Insert 0.50 -> CREDIT 0.50
Insert 0.50 -> CREDIT 1.00
Choose A1 (1.00) -> item stuck, not charged | CREDIT 1.00
Choose A1 (1.00) -> out of order | CREDIT 1.00
Choose A2 (1.50) -> sold out | CREDIT 1.00
Cancel -> returns 2 x 0.50 | INSERT COINS
-- the operator's visit
Operator opens door -> open | SERVICE
Insert 1.00 -> refused
Takes 2 x 2.00
coin box: 2 x 0.50 + 5 x 0.20 + 5 x 0.10
Insert 2.00 -> CREDIT 2.00
Choose B1 (1.40) -> sold: Crisps, change 1 x 0.50 + 1 x 0.10 | INSERT COINS

How to read it:

  1. The box starts with one 0.50 and three 0.20. The first sale owes 0.60, and the change is the three 0.20 coins, the case largest-first misses (AC-1.7). The box then holds the customer’s 2.00 and the 0.50.
  2. 1.00 is short of 1.50; the price is shown and the credit kept (AC-1.3). Another 0.50, and the last juice is sold with no change.
  3. Cancel returns the 0.50 and the 0.20 that were inserted (AC-2.1).
  4. The box now has 2.00, 1.00, and two 0.50: no 0.20 or 0.10, so 0.60 cannot be paid and the crisps are refused (AC-1.5). The operator cannot open the door (AC-3.1). The customer picks water instead and gets the 1.00 coin as change.
  5. A jam: nothing is charged, the slot is then out of order, the juice is sold out, and cancel returns the customer’s two 0.50 coins (AC-1.8, AC-1.4).
  6. The operator opens the door; a coin is refused (AC-3.2). The demo restocks A1, which clears its jam (AC-3.3; the demo does not sell from A1 again, the test ac_3_3_stocking_a_slot_again_clears_the_jam shows it). The operator takes the two 2.00 coins and loads small coins (AC-3.4), after which 0.60 change is 0.50 and 0.10.

The tests are in step-1/tests/test_step1.cpp, named after the acceptance criteria. They use a stand-in Dispenser that jams on the slots it is told to and counts how often a motor ran. See Test doubles and seams.

Change-making, alone, with no machine:

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

test_step1.cpp
// LLD_TEST(name) defines one test. LLD_CHECK(condition) records a failure
// if the condition is false; LLD_CHECK_EQ(a, b) does the same for a == b and
// prints both values when they differ; LLD_CHECK_THROWS(expression, type)
// fails unless the expression throws that type of exception. They come from
// the site's small test header, lld_test.hpp.
//
// coins({{Coin::c50, 1}, {Coin::c20, 3}}) is a helper defined above these
// tests (not shown): it builds a Coins from pairs of (coin, how many), here
// one 0.50 and three 0.20. Names start with the acceptance criterion they
// check, so ac_1_7 is AC-1.7.
LLD_TEST(ac_1_7_change_is_found_where_largest_first_without_backing_off_fails) {
// 0.60 from one 0.50 and three 0.20: taking the 0.50 first leaves
// 0.10, which no coin pays. Backing off finds 3 x 0.20.
const Coins box = coins({{Coin::c50, 1}, {Coin::c20, 3}});
LLD_CHECK(make_change(60, box) == coins({{Coin::c20, 3}}));
}
LLD_TEST(change_prefers_larger_coins_when_both_work) {
// 0.60 can be 3 x 0.20 or 0.50 + 0.10. The search tries the 0.50 first,
// so it must answer 0.50 + 0.10.
const Coins box = coins({{Coin::c50, 1}, {Coin::c20, 3}, {Coin::c10, 1}});
LLD_CHECK(make_change(60, box) == coins({{Coin::c50, 1}, {Coin::c10, 1}}));
}
LLD_TEST(change_is_nothing_when_no_combination_adds_up) {
// has_value() is false for an empty optional: "no change possible".
LLD_CHECK(!make_change(30, coins({{Coin::c20, 5}})).has_value()); // 0.20s cannot make 0.30
LLD_CHECK(!make_change(500, coins({{Coin::c200, 2}})).has_value()); // 4.00 is not enough
// Owing nothing is not a failure: the answer is an empty handful.
// Comparing an optional with a Coins compares the value inside it.
LLD_CHECK(make_change(0, Coins{}) == Coins{});
LLD_CHECK_THROWS(make_change(-10, Coins{}), std::invalid_argument);
}
// One test, 101 amounts: 0.00, 0.10, ... 10.00. For each, there must be an
// answer, it must add up exactly, and every coin in it must be in the box.
LLD_TEST(change_over_many_coins_is_exact) {
const Coins box = coins({{Coin::c10, 40}, {Coin::c20, 40}, {Coin::c50, 40}, {Coin::c100, 40}});
for (std::int64_t owed = 0; owed <= 1000; owed += 10) {
const std::optional<Coins> change = make_change(owed, box);
// change-> and *change reach the Coins inside the optional; the
// has_value() check comes first, and && stops at the first false.
LLD_CHECK(change.has_value() && change->total_cents() == owed && box.contains(*change));
}
}

The last test checks every amount from 0 to 10.00, in steps of 0.10, against a box of forty each of 0.10, 0.20, 0.50, and 1.00: the change always adds up and is always taken from coins that are there.

Sales. Each checks the answer and what did or did not move: the coin box, the count, the credit, and how often the motor ran.

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

test_step1.cpp
// Every sale test starts the same way. FakeDispenser (defined above, not
// shown) stands in for the motors: it reports a jam for the slots in its
// `jams` set and counts its calls in `releases`. stocked(motors, box)
// returns a machine with A1 water 1.00 x 2, A2 juice 1.50 x 1, and B1
// crisps 1.40 x 3, with `box` as its coins and the door closed.
LLD_TEST(ac_1_1_and_1_2_coins_add_credit_and_a_sale_pays_exact_change) {
FakeDispenser motors;
VendingMachine m = stocked(motors, coins({{Coin::c50, 1}, {Coin::c20, 3}}));
// std::string("...") makes both sides strings, so == compares the text.
LLD_CHECK_EQ(m.display(), std::string("INSERT COINS"));
LLD_CHECK(m.insert(Coin::c200));
LLD_CHECK_EQ(m.display(), std::string("CREDIT 2.00"));
const std::int64_t box_before = m.coin_box().total_cents();
const SaleResult r = m.choose("B1"); // 2.00 for 1.40: 0.60 owed
LLD_CHECK(r.status == SaleStatus::sold);
LLD_CHECK(r.change == coins({{Coin::c20, 3}}));
LLD_CHECK_EQ(m.coin_box().total_cents() - box_before, 140); // the box gains the price
LLD_CHECK_EQ(m.slot("B1").count, 2);
LLD_CHECK_EQ(m.credit_cents(), 0);
LLD_CHECK_EQ(m.display(), std::string("INSERT COINS"));
}
// A refused sale leaves the credit as it was, and the customer can add
// coins and try again. releases == 1 proves the motor ran only once.
LLD_TEST(ac_1_3_not_enough_credit_shows_the_price_and_keeps_the_credit) {
FakeDispenser motors;
VendingMachine m = stocked(motors, Coins{});
m.insert(Coin::c100);
const SaleResult r = m.choose("A2");
LLD_CHECK(r.status == SaleStatus::not_enough_credit);
LLD_CHECK_EQ(r.price_cents, 150);
LLD_CHECK_EQ(m.credit_cents(), 100);
m.insert(Coin::c50);
LLD_CHECK(m.choose("A2").status == SaleStatus::sold);
LLD_CHECK_EQ(motors.releases, 1);
}
LLD_TEST(ac_1_4_unknown_and_sold_out_slots_keep_the_credit) {
FakeDispenser motors;
VendingMachine m = stocked(motors, Coins{});
m.insert(Coin::c100);
m.insert(Coin::c50);
LLD_CHECK(m.choose("Z9").status == SaleStatus::unknown_slot);
LLD_CHECK_EQ(m.credit_cents(), 150);
LLD_CHECK(m.choose("A2").status == SaleStatus::sold); // the last juice
m.insert(Coin::c100);
m.insert(Coin::c50);
LLD_CHECK(m.choose("A2").status == SaleStatus::sold_out);
LLD_CHECK_EQ(m.credit_cents(), 150);
LLD_CHECK_EQ(motors.releases, 1);
}
// The box holds only 2.00 coins, so 0.60 cannot be paid. Nothing may move:
// the credit, the box, the count, and the motor (never run) are checked.
LLD_TEST(ac_1_5_no_exact_change_refuses_the_sale_and_keeps_the_credit) {
FakeDispenser motors;
VendingMachine m = stocked(motors, coins({{Coin::c200, 3}}));
m.insert(Coin::c200);
const SaleResult r = m.choose("B1"); // 0.60 owed, only 2.00 coins inside
LLD_CHECK(r.status == SaleStatus::no_change);
LLD_CHECK_EQ(m.credit_cents(), 200);
LLD_CHECK(m.coin_box() == coins({{Coin::c200, 3}}));
LLD_CHECK_EQ(m.slot("B1").count, 3);
LLD_CHECK_EQ(motors.releases, 0);
}
// The box is empty, so the 0.20 change can only come from the customer's
// own coins. After the sale the box keeps the rest of them: 1.00 + 2 x 0.20.
LLD_TEST(ac_1_6_change_can_use_the_coins_just_inserted) {
FakeDispenser motors;
VendingMachine m = stocked(motors, Coins{}); // an empty coin box
m.insert(Coin::c100);
m.insert(Coin::c20);
m.insert(Coin::c20);
LLD_CHECK(m.insert(Coin::c20));
const SaleResult r = m.choose("B1"); // 1.60 for 1.40
LLD_CHECK(r.status == SaleStatus::sold);
LLD_CHECK(r.change == coins({{Coin::c20, 1}}));
LLD_CHECK(m.coin_box() == coins({{Coin::c100, 1}, {Coin::c20, 2}}));
}

Jams, including that a jammed slot is not tried again and that restocking clears it:

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

test_step1.cpp
// A1 is set to jam. After the jam the credit, the empty box, and the count
// are unchanged, the slot is marked jammed, a second try is refused without
// running the motor, and cancel gives back the very coin inserted.
LLD_TEST(ac_1_8_a_jam_charges_nothing_and_puts_the_slot_out_of_order) {
FakeDispenser motors;
motors.jams.insert("A1");
VendingMachine m = stocked(motors, Coins{});
m.insert(Coin::c100);
LLD_CHECK(m.choose("A1").status == SaleStatus::jammed);
LLD_CHECK_EQ(m.credit_cents(), 100);
LLD_CHECK(m.coin_box() == Coins{});
LLD_CHECK_EQ(m.slot("A1").count, 2);
LLD_CHECK(m.slot("A1").jammed);
// The slot is not tried again; nobody else pays for a stuck item.
LLD_CHECK(m.choose("A1").status == SaleStatus::out_of_order);
LLD_CHECK_EQ(motors.releases, 1);
LLD_CHECK(m.cancel() == coins({{Coin::c100, 1}}));
}
// Jam A1, then fix the motor and restock A1 with the door open. The next
// sale from A1 works, and the count is 5 - 1 = 4.
LLD_TEST(ac_3_3_stocking_a_slot_again_clears_the_jam) {
FakeDispenser motors;
motors.jams.insert("A1");
VendingMachine m = stocked(motors, Coins{});
m.insert(Coin::c100);
m.choose("A1"); // jams; the result is not needed here
m.cancel(); // credit must be gone before the door can open
motors.jams.clear();
LLD_CHECK(m.open_door());
m.stock("A1", "Water", 100, 5);
m.close_door();
m.insert(Coin::c100);
LLD_CHECK(m.choose("A1").status == SaleStatus::sold);
LLD_CHECK_EQ(m.slot("A1").count, 4);
}

Cancel and the door are in the cancel-tests and door-tests regions of the same file.

Invariants. One test runs sixty rounds of coins, sales, jams, cancels, and the operator clearing jams, and after each round checks INV-1 coin by coin and INV-2 for each sale. It also checks that the rounds really sell and really jam (18 sales and 5 jams when written), because a mixed test that never reaches a jam checks nothing about jams:

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

test_step1.cpp
LLD_TEST(inv_1_and_inv_2_every_coin_is_accounted_for) {
// INV-1: coins inside (box + escrow) = loaded + inserted - returned.
// INV-2: each sale adds exactly its price to the box.
// The test keeps its own record of every coin that went in (loaded,
// inserted) and came out (returned: change and cancels), and after each
// round compares that record with the coins really inside the machine.
FakeDispenser motors;
const Coins loaded = coins({{Coin::c50, 2}, {Coin::c20, 4}, {Coin::c10, 3}});
VendingMachine m = stocked(motors, loaded);
// Plenty of stock, so sixty rounds never sell out.
m.open_door();
m.stock("A1", "Water", 100, 50);
m.stock("B1", "Crisps", 140, 50);
m.close_door();
Coins inserted;
Coins returned;
int sold = 0;
int jammed = 0;
const std::vector<Coin> pattern{Coin::c200, Coin::c50, Coin::c20, Coin::c100, Coin::c10};
for (int round = 0; round < 60; ++round) {
// The coins repeat in a cycle of five: round 0 gets 2.00, round 1
// 0.50, ... round 5 2.00 again. `%` is the remainder after division.
const Coin coin = pattern[static_cast<std::size_t>(round) % pattern.size()];
m.insert(coin);
inserted.add(coin);
// In each cycle of seven rounds, A1 starts jamming at round 3 and
// the operator clears it at round 5 (3, 10, 17, ... and 5, 12, ...).
if (round % 7 == 3) motors.jams.insert("A1");
if (round % 7 == 5) {
// The operator clears the jam: cancel, open, restock, close.
motors.jams.clear();
returned.add(m.cancel());
m.open_door();
m.stock("A1", "Water", 100, 50);
m.close_door();
m.insert(coin);
inserted.add(coin);
}
const std::int64_t box_before = m.coin_box().total_cents();
// Even rounds try water from A1, odd rounds crisps from B1.
const SaleResult r = m.choose(round % 2 == 0 ? "A1" : "B1");
if (r.status == SaleStatus::jammed) ++jammed;
if (r.status == SaleStatus::sold) {
++sold;
returned.add(r.change);
LLD_CHECK_EQ(m.coin_box().total_cents() - box_before, r.price_cents);
}
// Every fifth round the customer cancels whatever credit is left
// (often none, after a sale).
if (round % 5 == 4) returned.add(m.cancel());
// INV-1, coin by coin: box plus escrow equals what the record says.
Coins inside = m.coin_box();
inside.add(m.escrow());
Coins expected = loaded;
expected.add(inserted);
expected.remove(returned);
LLD_CHECK(inside == expected);
}
// The rounds really sell and really jam (18 and 5 when this was written).
LLD_CHECK(sold >= 15 && jammed >= 5);
}

Did the tests check enough? The step 1 code was changed by hand in ten small ways, one at a time, and the tests run after each: <= for < in the credit check, trying fewer coins first in the search, never backing off, leaving the inserted coins out of the change, not marking a jam, not taking the change out of the box, opening the door with credit, keeping the credit after cancel, and keeping a jam after restocking. Each of those nine made at least one test fail. The tenth made the search’s early stop less strict; the tests still passed, which is right, since it changes only how long the search takes, not its answer.

Run them with:

Terminal window
cd examples
cmake --preset gcc-debug && cmake --build --preset gcc-debug
ctest --preset gcc-debug -R cs_vending

The design is single-threaded, and for one machine with one keypad that is the right choice. Two things still need care on real hardware.

  1. Events arrive from different places. The coin acceptor, the keypad, the door switch, and (after the change) the card reader each signal on their own, often from interrupt handlers or driver threads. Calling insert from one thread while choose runs on another would race on state_ and box_. The usual answer is not a lock in every function but one queue: each source pushes an event, and one thread takes events from the queue and calls the machine. The machine stays as it is. See Thread safety and synchronization.
  2. Power can fail mid-sale. The inserted coins are only a record in memory; the coins themselves have fallen into the machine. If the power fails, the credit is gone but the coins are inside, with no record of whose they were. If the power fails after the item dropped but before the sale was committed, the slot’s count is one too high, the customer’s coins are inside but not in the box’s record, and the change was never paid. A real machine records the credit in non-volatile memory as each coin arrives, and writes “selling B1, change 3 x 0.20” before the motor runs, so that after a restart it knows a sale may have happened. That is a write-ahead record, the same idea a database uses.

A year later, the client adds a card reader.

“Customers should be able to pay by card, one item at a time. If the item gets stuck, the card must not be charged.”

New requirements:

  • FR-9 A customer can choose a slot to pay by card, then present a card. The machine shows the price while it waits.
  • FR-10 The card is charged only if the item drops. The machine reserves the price on the card first, releases the item, and then takes the reserved money, or cancels the reservation on a jam.
  • FR-11 A sale is paid by coins or by card, not both. During a card sale coins are refused and the door stays shut; with coins inside, a card sale is refused.

UC-4 Buy with a card.

  • AC-4.1 For an available slot, the machine shows “PRESENT CARD” and the price. When the card is presented it reserves the price, releases the item, and then captures the reservation, in that order.
  • AC-4.2 A declined card releases nothing, and the machine is idle.
  • AC-4.3 A jam cancels the reservation, never captures it, and puts the slot out of order.
  • AC-4.4 Cancel during a card sale ends it with nothing reserved.
  • AC-4.5 During a card sale, coins are refused and the door stays shut. Pressing a slot button shows the card sale’s price again.
  • AC-4.6 With coins inside, a card sale is refused and the credit is kept.
  • AC-4.7 Choosing another slot replaces the card sale; an unknown or unavailable slot leaves the current one in place.

The card provider offers two calls: authorize (reserve an amount on the card) and capture (take the reserved amount). Charging in one call before the motor runs would mean a refund after a jam: a second call that can fail, and money the customer sees leave and come back days later. Charging after the motor runs would hand over an item before knowing the card is good. Reserving first answers “is the card good?” before the item drops, and capturing after means a jam needs only a cancel, which costs the customer nothing. It is the same “plan, drop, commit” order as the coin sale.

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

card_payments.hpp
// The provider's name for one reservation, needed later to capture or
// cancel it. A struct around the number, rather than a bare std::uint64_t,
// so it cannot be mixed up with an amount or any other number by accident.
// `= default` asks the compiler to write == (compare the values).
struct AuthorizationId {
std::uint64_t value = 0;
friend bool operator==(const AuthorizationId&, const AuthorizationId&) = default;
};
// The card provider, as the machine sees it: an interface with three calls,
// reserve (authorize), take (capture), and release (cancel). The machine
// holds a CardPayments& and does not own it; tests give it a fake.
class CardPayments {
public:
virtual ~CardPayments() = default; // so a derived class is destroyed properly
// Reserves the amount on the card; nothing if the provider declines.
// card_token is what the reader gives, never a card number. May
// throw if the provider cannot be reached; nothing is reserved then.
// The std::optional is empty for "declined" and holds the id otherwise.
virtual std::optional<AuthorizationId> authorize(const std::string& card_token,
std::int64_t cents) = 0;
// Takes the reserved money. Called only after the item has dropped,
// so it must not fail here: an implementation that cannot reach the
// provider queues the capture and sends it later. noexcept promises that
// no exception leaves the function; if one did, the program would stop.
virtual void capture(AuthorizationId id) noexcept = 0;
// Releases the reservation; the customer pays nothing. Queued the same
// way if the provider cannot be reached.
virtual void cancel(AuthorizationId id) noexcept = 0;
};

capture and cancel are noexcept. That is a contract on whoever implements the interface: once the item is in the tray, the machine has no sensible way to handle “capture failed”. The compiler holds implementers to part of it: an override of a noexcept virtual function must itself be noexcept, and an exception that escapes one ends the program through std::terminate. A real adapter stores the capture and sends it when the network is back, which card terminals do. authorize may throw, because nothing has happened yet when it does.

One new state carries the chosen slot:

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

machine.hpp
// As in step 1, each state holds only the data that exists in it.
struct Idle {}; // door shut, nobody buying
struct HasCredit {
Coins escrow; // the customer's own coins, never empty in this state
};
// New in step 2: the customer chose a slot to pay by card and the machine
// waits for the card. It holds the slot's code, a plain string, rather than
// a pointer to the Slot: the slot is looked up again when the card comes.
// It has no coins, because a card sale takes none (FR-11).
struct AwaitingCard {
std::string slot; // chosen, in stock, and not jammed when chosen
};
struct Maintenance {}; // the door is open
// One more alternative in the variant. Every std::visit over State must now
// say what to do with an AwaitingCard, or it does not compile.
using State = std::variant<Idle, HasCredit, AwaitingCard, Maintenance>;
The states of the machine in step 2: the card sale is one more state
Text description of the diagram

Four states. Everything from step 1 is unchanged: Maintenance to Idle on close_door, Idle to HasCredit on a coin, HasCredit back to Idle on a sale or cancel, and Idle to Maintenance on open_door. New: in Idle, choose_card for an available slot moves to AwaitingCard. In AwaitingCard, choose_card for another available slot stays in AwaitingCard with the new slot. present_card moves back to Idle whether the item was sold, the card was declined, or the item jammed. If the provider or the motor controller throws, present_card leaves the machine in AwaitingCard. cancel also moves back to Idle. In AwaitingCard, coins are refused and open_door is refused. In HasCredit, choose_card is refused.

Diagram source (Mermaid)
stateDiagram-v2
[*] --> Maintenance : installed, door open
Maintenance --> Idle : close_door
Idle --> HasCredit : insert coin
HasCredit --> Idle : sale with change, or cancel
Idle --> AwaitingCard : choose_card [slot available]
AwaitingCard --> AwaitingCard : choose_card [another slot]
AwaitingCard --> Idle : present_card [sold, declined, or jammed]
AwaitingCard --> AwaitingCard : present_card [provider or motor fault]
AwaitingCard --> Idle : cancel
Idle --> Maintenance : open_door

The compiler finds the places to update. Adding AwaitingCard to State and building the step 1 machine.cpp against it fails at exactly five places, the five std::visit calls: insert, choose, cancel, open_door, and display. Each Overloaded set has no branch that accepts an AwaitingCard, so std::visit cannot be instantiated. (This was checked with GCC 11. The messages are long, but each points at the line of its visit.) The query escrow(), which uses std::get_if<HasCredit>, and the door check, which uses std::holds_alternative<Maintenance>, still compile, and are still right: an AwaitingCard has no inserted coins and is not the service state.

That is the reason the actions were written as visits. Compare a version that tests one state at a time:

Flawed (intentional)Demonstrates a mistake on purpose. Do not copy it; see the corrected version.

// Tests the states one at a time instead of visiting them. Before step 2,
// it is correct: the last part runs only in Idle.
bool VendingMachine::insert(Coin coin) {
// holds_alternative asks "is the state a Maintenance right now?".
if (std::holds_alternative<Maintenance>(state_)) return false;
// get_if gives a pointer to the HasCredit inside state_, or nullptr if
// the state is something else; the `if` runs only for a HasCredit.
if (auto* credit = std::get_if<HasCredit>(&state_)) {
credit->escrow.add(coin); // adds to the coins inside state_, through the pointer
return true;
}
// Meant for Idle. After the change, AwaitingCard also arrives here:
// the card sale is dropped without a word and the coin is accepted.
// The compiler cannot warn: "everything else" quietly includes any
// state added later, which is exactly where it goes wrong.
Coins escrow;
escrow.add(coin);
state_ = HasCredit{escrow};
return true;
}

It compiles before and after the change, and after the change it is wrong. The corrected step 2 version answers every state, and the new branch is short:

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

machine.cpp
// Every customer action is a visit over the state, so each state must
// say what the action means in it. The visitor reads the current state
// and returns the next one; state_ is assigned only after the visit has
// finished, so no visitor replaces the object it is reading.
// std::visit calls the lambda in the Overloaded set whose parameter matches
// the state now held; step 1 explains the pieces. Step 2 adds one lambda,
// for AwaitingCard; without it this function would not compile.
bool VendingMachine::insert(Coin coin) {
bool accepted = true; // set to false by the lambdas that refuse the coin
state_ = std::visit(Overloaded{
[&](const Idle&) -> State {
// The first coin starts a new credit.
Coins escrow;
escrow.add(coin);
return HasCredit{escrow};
},
[&](const HasCredit& now) -> State {
// A copy of the credit with one more coin.
HasCredit next = now;
next.escrow.add(coin);
return next;
},
[&](const AwaitingCard& now) -> State {
accepted = false; // a card sale takes no coins
return now; // the card sale goes on, unchanged
},
[&](const Maintenance&) -> State {
accepted = false;
return Maintenance{};
},
},
state_);
return accepted;
}

The new actions:

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

machine.cpp
// The customer pressed "pay by card" and a slot button. If the slot can
// sell, the machine moves to AwaitingCard and shows "PRESENT CARD" with the
// price; nothing is reserved on any card yet. Returns present_card on
// success, or the reason it was refused: coins_inserted, unavailable (door
// open), or, from start_card_sale, unknown_slot, out_of_order, or sold_out.
SaleResult VendingMachine::choose_card(const std::string& code) {
// Assume success; the refusing branches overwrite the status.
SaleResult result{SaleStatus::present_card, {}, 0};
state_ = std::visit(Overloaded{
[&](const Idle& now) -> State {
// now (an Idle) becomes the State to keep if
// the slot cannot sell.
return start_card_sale(code, now, result);
},
[&](const HasCredit& now) -> State {
result.status = SaleStatus::coins_inserted;
return now; // pay with the coins, or cancel first
},
[&](const AwaitingCard& now) -> State {
return start_card_sale(code, now, result); // a new choice
},
[&](const Maintenance&) -> State {
result.status = SaleStatus::unavailable;
return Maintenance{};
},
},
state_);
return result;
}
// The checks shared by the Idle and AwaitingCard branches: the same three
// checks as the start of a coin sale (slot exists, not jammed, in stock),
// without the credit and change checks, which do not apply to a card.
// In: the slot code; otherwise, the state to stay in if a check fails
// (Idle, or the current card sale, so a bad choice keeps it, AC-4.7);
// result, which gets the status and the price.
// Out: AwaitingCard for the slot if every check passes, else otherwise.
// `const State& otherwise` accepts an Idle or an AwaitingCard: each turns
// into a temporary State holding a copy of it, so returning otherwise
// returns a copy, never a reference into state_.
State VendingMachine::start_card_sale(const std::string& code, const State& otherwise,
SaleResult& result) {
const Slot* slot = find(code);
if (slot == nullptr) {
result.status = SaleStatus::unknown_slot;
return otherwise;
}
result.price_cents = slot->price_cents;
if (slot->jammed) {
result.status = SaleStatus::out_of_order;
return otherwise;
}
if (slot->count == 0) {
result.status = SaleStatus::sold_out;
return otherwise;
}
// A new card sale for this slot. From AwaitingCard this replaces the
// earlier choice; nothing had been reserved for it, so nothing is lost.
return AwaitingCard{code};
}

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

machine.cpp
// The customer held a card to the reader; card_token is what the reader
// passes on. Only AwaitingCard has a sale to pay for. In every other state
// nothing happens and the answer is no_card_sale.
// Exceptions from the provider or the motor pass straight through to the
// caller. std::visit then never returns, so the assignment to state_ never
// happens and the machine stays in AwaitingCard.
SaleResult VendingMachine::present_card(const std::string& card_token) {
SaleResult result{SaleStatus::no_card_sale, {}, 0};
state_ = std::visit(Overloaded{
[](const Idle&) -> State { return Idle{}; },
[](const HasCredit& now) -> State { return now; }, // keep the credit
[&](const AwaitingCard& now) -> State {
return pay_by_card(now, card_token, result);
},
[](const Maintenance&) -> State { return Maintenance{}; },
},
state_);
return result;
}
// The card sale itself: reserve the price, run the motor, then take the
// money if the item dropped or release the reservation if it did not.
// sale is a reference into state_; it stays valid because nothing here
// assigns to state_ (present_card does that after the visit).
// Out: Idle after sold, declined, or jammed. An exception from authorize or
// release goes on to the caller; for release, the reservation is cancelled
// first.
State VendingMachine::pay_by_card(const AwaitingCard& sale, const std::string& token,
SaleResult& result) {
// The slot was in stock when chosen, and nothing can change it since:
// stocking needs the door open, and the door stays shut during a sale.
// at() finds the slot by its code (it would throw std::out_of_range for
// a missing one, but every code in an AwaitingCard was found in slots_).
Slot& slot = slots_.at(sale.slot);
result.price_cents = slot.price_cents;
// Reserve, release, then take: the customer pays only for an item
// that dropped. If authorize throws, nothing is reserved and the sale
// stays open, so the customer can present the card again.
// Step 1, reserve. hold is empty if the card was declined.
const std::optional<AuthorizationId> hold = cards_.authorize(token, slot.price_cents);
if (!hold) { // declined: nothing reserved, nothing released
result.status = SaleStatus::declined;
return Idle{};
}
// Step 2, release the item. The money is now reserved, so if the motor
// controller throws, the reservation must be cancelled before the
// exception goes on. catch (...) catches an exception of any type, and
// a bare `throw;` sends that same exception on to the caller.
bool dropped = false;
try {
dropped = dispenser_.release(sale.slot);
} catch (...) {
cards_.cancel(*hold); // the money must not stay reserved
throw;
}
// Step 3, take the money or give it back.
if (!dropped) { // jammed: mark the slot, release the reservation
slot.jammed = true;
cards_.cancel(*hold);
result.status = SaleStatus::jammed;
return Idle{};
}
--slot.count;
cards_.capture(*hold); // noexcept: the item is already in the tray
result.status = SaleStatus::sold;
return Idle{};
}
How this code works: choose_card, present_card, and pay_by_card

Choosing. choose_card is a visit like the others. From Idle, and from an AwaitingCard, it calls start_card_sale, which runs the slot checks and returns either a new AwaitingCard for the slot or otherwise, the state it was given. So from Idle a bad slot leaves the machine Idle, and during a card sale a bad slot keeps the current sale (AC-4.7). With coins inside it refuses (coins_inserted), and with the door open it answers unavailable. No card has been touched yet.

Paying. present_card does something only in AwaitingCard; there it calls pay_by_card, which does three things in order:

  1. Reserve. authorize asks the provider to hold the price on the card. An empty answer means declined: the sale ends, nothing dropped.
  2. Release. The motor runs. If it throws, the catch (...) block cancels the reservation and throw; passes the same exception on.
  3. Take or give back. If the item dropped, the count goes down and capture takes the reserved money. If it jammed, the slot is marked jammed and cancel releases the reservation.

When something throws, the exception leaves pay_by_card, the lambda, and std::visit before state_ = ... runs. So state_ keeps the AwaitingCard, and the customer can present the card again or cancel.

Every outcome, with the values from the step 2 tests:

Case Log of the fakes present_card gives State after
A2 (1.50), the item drops authorize 150, release A2, capture 1 sold Idle, A2’s count 1 to 0
A1, token "declined" (nothing) declined Idle
B1 (1.40), the item jams authorize 140, release B1, cancel 1 jammed Idle, B1 marked jammed
A1, token "offline" (provider throws) (nothing) throws std::runtime_error still AwaitingCard
A1 (1.00), the motor throws authorize 100, cancel 1 throws std::runtime_error still AwaitingCard

In every row, money is taken (capture) only after an item dropped, and a reservation never stays open after a jam or a motor fault.

pay_by_card looks the slot up again with slots_.at rather than keeping a pointer in AwaitingCard. A pointer into the std::map would in fact stay valid (map nodes do not move), but the state would then depend on how the slots are stored, and copying the state would copy a pointer with no owner. The slot code is a plain value. The slot cannot have changed since it was chosen, because stocking needs the door open and the door stays shut during a card sale.

If the motor controller throws after the reservation, the catch cancels the reservation and rethrows. The sale stays open, and the customer can present the card again or cancel.

What else moved, and what did not. The constructor now also takes a CardPayments&, and open_door gained one branch (it is one of the five visits). Coins, make_change, Dispenser, sell, the coin box, stock, load_coins, and take_coins are unchanged. The step 1 tests would not compile against step 2 as they are, because they build the machine without a CardPayments; two coin checks are repeated in test_step2.cpp, and the step 1 suite is not rerun against step 2. SaleStatus gained four values (present_card, declined, coins_inserted, no_card_sale). The demo’s switch over it has no default, so under -Wall (which includes -Wswitch) and -Werror a status without a message would stop the build.

A card sale in step 2: reserve, release, then capture or cancel
Text description of the diagram

The customer chooses A2 to pay by card, and the machine shows PRESENT CARD 1.50. The customer presents a card. The machine asks CardPayments to authorize 1.50 on the card and gets authorization 1. It then asks the Dispenser to release A2. If an item dropped, the machine captures authorization 1 and reports “sold”. If the item jammed, the machine cancels authorization 1 and reports that the item is stuck and the customer was not charged. In both cases the machine returns to Idle.

Diagram source (Mermaid)
sequenceDiagram
participant C as customer
participant M as VendingMachine
participant P as CardPayments
participant D as Dispenser
C->>M: choose_card(A2)
M-->>C: PRESENT CARD 1.50
C->>M: present_card(token)
M->>P: authorize(token, 150)
P-->>M: authorization 1
M->>D: release(A2)
alt an item dropped
  D-->>M: true
  M->>P: capture(1)
  M-->>C: sold
else jammed
  D-->>M: false
  M->>P: cancel(1)
  M-->>C: item stuck, not charged
end

The stand-ins for the card provider and the motors write to one shared log, so a test can check the order of the calls:

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

test_step2.cpp
// Both stand-ins write to one log, so a test can check the order of
// what happened at the card provider and at the motors.
// `using Log = ...` gives the type a short name: a list of lines of text.
using Log = std::vector<std::string>;
// Stands in for the motors. It reports a jam for the slots in `jams`, and
// throws if `broken` is set, as a motor controller that stopped answering
// would. Each release it runs is written to the log first.
// `final` means no class can derive from it. `explicit` stops a Log from
// turning into a FakeDispenser by accident. log_ is a reference: the log
// belongs to the test, which must keep it alive longer than the fake.
class FakeDispenser final : public Dispenser {
public:
explicit FakeDispenser(Log& log) : log_(log) {}
bool release(const std::string& slot) override {
// A broken motor throws before logging, so a test can see that the
// release never happened.
if (broken) throw std::runtime_error("motor controller not responding");
log_.push_back("release " + slot);
return jams.count(slot) == 0;
}
std::set<std::string> jams;
bool broken = false;
private:
Log& log_;
};
// Approves every token except "declined"; throws for "offline".
// capture and cancel only write to the log, with the reservation's number.
class FakeCards final : public CardPayments {
public:
explicit FakeCards(Log& log) : log_(log) {}
// The token chooses the provider's answer, so each test picks its case
// by the card it presents. Only a successful authorize is logged, so a
// log line "authorize 150" means 1.50 really was reserved.
std::optional<AuthorizationId> authorize(const std::string& token,
std::int64_t cents) override {
if (token == "offline") throw std::runtime_error("provider unreachable");
if (token == "declined") return std::nullopt; // an empty optional: declined
log_.push_back("authorize " + std::to_string(cents));
// ++last_ adds one first and then gives the new value, so the
// first reservation is 1, the next 2, and so on.
return AuthorizationId{++last_};
}
void capture(AuthorizationId id) noexcept override {
log_.push_back("capture " + std::to_string(id.value));
}
void cancel(AuthorizationId id) noexcept override {
log_.push_back("cancel " + std::to_string(id.value));
}
private:
Log& log_;
std::uint64_t last_ = 0;
};

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

test_step2.cpp
// Each test starts with `Rig rig;`. Rig is a small struct defined above
// (not shown) that holds one shared Log, the two fakes writing to it, and a
// machine using both, stocked as in step 1 (A1 water 1.00 x 2, A2 juice
// 1.50 x 1, B1 crisps 1.40 x 3) with the door closed. The members are
// created in the order they are written, so the log and the fakes exist
// before the machine that refers to them. rig.log is then the story of
// what happened at the provider and the motors, in order.
LLD_TEST(ac_4_1_a_card_sale_reserves_releases_then_captures) {
Rig rig;
const SaleResult chosen = rig.machine.choose_card("A2");
LLD_CHECK(chosen.status == SaleStatus::present_card);
LLD_CHECK_EQ(rig.machine.display(), std::string("PRESENT CARD 1.50"));
LLD_CHECK(rig.log.empty()); // nothing is reserved until the card is presented
const SaleResult r = rig.machine.present_card("card-1");
LLD_CHECK(r.status == SaleStatus::sold);
// The order is the point: reserve 1.50, drop the item, then take
// reservation 1. Log({...}) builds the expected list to compare with.
LLD_CHECK(rig.log == Log({"authorize 150", "release A2", "capture 1"}));
LLD_CHECK_EQ(rig.machine.slot("A2").count, 0);
LLD_CHECK(rig.machine.coin_box() == Coins{}); // no coins were involved
LLD_CHECK_EQ(rig.machine.display(), std::string("INSERT COINS"));
}
// The fake declines the token "declined" without logging, so an empty log
// proves the motor never ran; the count is still 2 and the machine is idle.
LLD_TEST(ac_4_2_a_declined_card_releases_nothing) {
Rig rig;
rig.machine.choose_card("A1");
LLD_CHECK(rig.machine.present_card("declined").status == SaleStatus::declined);
LLD_CHECK(rig.log.empty());
LLD_CHECK_EQ(rig.machine.slot("A1").count, 2);
LLD_CHECK_EQ(rig.machine.display(), std::string("INSERT COINS"));
}
// B1 jams: the reservation is cancelled, never captured, the slot is out
// of order, and its count is unchanged.
LLD_TEST(ac_4_3_a_jam_cancels_the_reservation_and_never_captures) {
Rig rig;
rig.motors.jams.insert("B1");
rig.machine.choose_card("B1");
LLD_CHECK(rig.machine.present_card("card-1").status == SaleStatus::jammed);
LLD_CHECK(rig.log == Log({"authorize 140", "release B1", "cancel 1"}));
LLD_CHECK(rig.machine.slot("B1").jammed);
LLD_CHECK_EQ(rig.machine.slot("B1").count, 3);
LLD_CHECK(rig.machine.choose_card("B1").status == SaleStatus::out_of_order);
}
// Cancel during a card sale returns no coins and ends it, so a card
// presented afterwards finds no sale, and the provider was never called.
LLD_TEST(ac_4_4_cancel_ends_a_card_sale_with_nothing_reserved) {
Rig rig;
rig.machine.choose_card("A1");
LLD_CHECK(rig.machine.cancel() == Coins{});
LLD_CHECK(rig.machine.present_card("card-1").status == SaleStatus::no_card_sale);
LLD_CHECK(rig.log.empty());
}
// During a card sale for A1: a coin is refused, the door stays shut, and
// pressing another slot button only shows A1's sale and price again.
LLD_TEST(ac_4_5_a_card_sale_takes_no_coins_and_keeps_the_door_shut) {
Rig rig;
rig.machine.choose_card("A1");
LLD_CHECK(!rig.machine.insert(Coin::c100));
LLD_CHECK_EQ(rig.machine.credit_cents(), 0);
LLD_CHECK(!rig.machine.open_door());
const SaleResult pressed = rig.machine.choose("B1"); // the card sale is still for A1
LLD_CHECK(pressed.status == SaleStatus::present_card);
// std::int64_t{100} so both sides have the same integer type.
LLD_CHECK_EQ(pressed.price_cents, std::int64_t{100});
LLD_CHECK_EQ(rig.machine.display(), std::string("PRESENT CARD 1.00"));
}
// With 0.50 inserted, choose_card is refused, the credit is kept, and
// cancel returns that very coin.
LLD_TEST(ac_4_6_with_coins_inside_a_card_sale_is_refused) {
Rig rig;
rig.machine.insert(Coin::c50);
LLD_CHECK(rig.machine.choose_card("A1").status == SaleStatus::coins_inserted);
LLD_CHECK_EQ(rig.machine.credit_cents(), 50);
LLD_CHECK(rig.machine.cancel() == coins({{Coin::c50, 1}}));
}
// Choose A1, then the unknown Z9: the A1 sale (1.00) is kept. Then choose
// B1: it replaces A1, and the card pays 1.40 for B1.
LLD_TEST(ac_4_7_choosing_again_replaces_the_card_sale_and_bad_choices_keep_it) {
Rig rig;
rig.machine.choose_card("A1");
LLD_CHECK(rig.machine.choose_card("Z9").status == SaleStatus::unknown_slot);
LLD_CHECK_EQ(rig.machine.display(), std::string("PRESENT CARD 1.00")); // still A1
LLD_CHECK(rig.machine.choose_card("B1").status == SaleStatus::present_card);
LLD_CHECK(rig.machine.present_card("card-1").status == SaleStatus::sold);
LLD_CHECK(rig.log == Log({"authorize 140", "release B1", "capture 1"}));
}
// A card in Idle, and then in HasCredit, does nothing: no provider call,
// and the 1.00 credit is untouched.
LLD_TEST(a_card_presented_when_none_was_asked_for_does_nothing) {
Rig rig;
LLD_CHECK(rig.machine.present_card("card-1").status == SaleStatus::no_card_sale);
rig.machine.insert(Coin::c100);
LLD_CHECK(rig.machine.present_card("card-1").status == SaleStatus::no_card_sale);
LLD_CHECK_EQ(rig.machine.credit_cents(), 100);
LLD_CHECK(rig.log.empty());
}

Two tests cover failures at the edges, a provider that cannot be reached and a motor controller that throws:

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

test_step2.cpp
// The token "offline" makes the fake's authorize throw. The exception
// reaches the test, nothing was logged (nothing reserved, no motor), and the
// sale is still open: presenting a good card afterwards sells the item.
LLD_TEST(an_unreachable_provider_leaves_the_card_sale_open) {
Rig rig;
rig.machine.choose_card("A1");
LLD_CHECK_THROWS(rig.machine.present_card("offline"), std::runtime_error);
LLD_CHECK(rig.log.empty());
LLD_CHECK_EQ(rig.machine.display(), std::string("PRESENT CARD 1.00"));
LLD_CHECK(rig.machine.present_card("card-1").status == SaleStatus::sold);
}
// The motor controller throws after 1.00 was reserved. pay_by_card's catch
// cancels reservation 1 and rethrows, so the log shows authorize then
// cancel, with no release line (the broken fake throws before logging) and
// no capture. The count is unchanged and the sale stays open.
LLD_TEST(a_motor_fault_after_authorizing_cancels_the_reservation) {
Rig rig;
rig.motors.broken = true;
rig.machine.choose_card("A1");
LLD_CHECK_THROWS(rig.machine.present_card("card-1"), std::runtime_error);
LLD_CHECK(rig.log == Log({"authorize 100", "cancel 1"}));
LLD_CHECK_EQ(rig.machine.slot("A1").count, 2);
LLD_CHECK_EQ(rig.machine.display(), std::string("PRESENT CARD 1.00"));
}

The step 2 file also repeats two step 1 checks (a coin sale with change, and the cancel and door rules) to show that the coin behaviour is unchanged. The full step 1 suite is not copied.

Expected output
-- card sale
Card for A2 -> present card | PRESENT CARD 1.50
provider: reserved 1.50 as #1
motor A2: dropped
provider: captured #1
Present card -> sold | INSERT COINS
-- declined
Card for A1 -> present card | PRESENT CARD 1.00
provider: declined
Present card -> card declined | INSERT COINS
-- a coin during a card sale
Card for B1 -> present card | PRESENT CARD 1.40
Insert 1.00 -> refused
Operator opens door -> refused, sale in progress
Cancel -> returns none | INSERT COINS
-- a jam
Card for A1 -> present card | PRESENT CARD 1.00
provider: reserved 1.00 as #2
motor A1: jammed
provider: cancelled #2
Present card -> item stuck, not charged | INSERT COINS
Card for A1 -> out of order | INSERT COINS
-- coins, as before
Card for B1 with 2.00 inside -> pay with your coins or cancel first | CREDIT 2.00
motor B1: dropped
Choose B1 -> sold, change 3 x 0.20 | INSERT COINS

The provider’s and the motor’s lines appear before the result line of each action, because they happen while the action runs. In the jam, the reservation (#2) is cancelled and never captured (AC-4.3). In the last part, a card sale is refused while 2.00 of coins is inside (AC-4.6), and the coin sale that follows still pays 3 x 0.20 change.

In a 45-minute interview you will not write all of this. A plan that fits the time boxes from The design workflow:

Time What to do What to say
About 5 min Ask about coins, change, what cancel returns, jams, and the door. Write FR-1 … FR-8 and an out-of-scope list. “Cancel returning the same coins means the inserted coins are kept apart until a sale.”
3–5 min Sketch VendingMachine, Coins, Slot, Dispenser, and the three states. Say what is not a class: product, coin, door. “Credit, change, and the coin box are all the same thing: some coins of each kind.”
10–15 min Draw the state diagram; write the State variant; outline the machine with owners; state INV-1 and INV-3. “The inserted coins live inside HasCredit, so ‘door open with credit’ cannot be represented.”
10–15 min Write make_change and sell; trace the 0.60 case and a jam. “Plan, drop, then commit: a jam needs no undo because nothing moved.”
About 5 min Take the card change: one new state, and reserve before the item drops. “Adding the state breaks the build at every visit, which is the list of places to decide.”

What is usually expected at each level

Level Usually expected
Junior Asks about coins and change; draws the states; writes a working sale and cancel; handles not enough credit and sold out; uses integer cents.
Mid-level All of the above, plus: keeps the inserted coins apart for cancel; spots that largest-first change can fail with a limited box; orders the sale so a jam costs nothing; justifies the state representation; names tests by AC.
Senior All of the above, plus: makes the bad states unrepresentable and explains the visit’s compile-time check; raises events from several hardware sources and power loss mid-sale; explains authorize and capture for the card change.

These are this site’s judgement of common practice, as on How to approach a case study, not any company’s rubric.

  • Coin tubes fill up. Real machines keep change in tubes of fixed size and send extra coins to a cash box that cannot pay change. The model has one box of unlimited size, so it never needs to say “exact change only”.
  • The drop sensor is trusted. If it misses a falling item, the customer gets it free; if it sees one that did not fall, the customer pays for nothing. Real machines add a “my item did not drop” refund request and an audit log.
  • Power loss loses the credit; see concurrency and persistence.
  • No timeouts. An abandoned card sale waits until someone presses cancel. The exercise adds one.
  • Card payment is a stand-in. Real providers add network timeouts, reservations that expire, and partial approvals. capture and cancel are assumed to be queued by the adapter.
  • One thread, one keypad. Hardware events need one queue in front of the machine.
  • The change search was not measured. Its worst case grows with the number of coins in the box; it is small for these coins and amounts.
  • No reports or telemetry. Sales, jams, and coin levels are not recorded anywhere.
Requirement Design element Code Tests Status
FR-1 stocking VendingMachine::stock, Slot step 1 machine.cpp ac_3_3_stocking_rejects_bad_prices_counts_and_slots, ac_3_3_stocking_a_slot_again_clears_the_jam Tested
FR-2 coins and credit Coin, Coins, HasCredit coins.hpp, insert ac_1_1_and_1_2_coins_add_credit_and_a_sale_pays_exact_change Tested
FR-3 a sale choose, sell step 1 machine.cpp ac_1_1_and_1_2_…, ac_1_3_…, ac_1_4_… Tested
FR-4 cancel returns the same coins HasCredit::escrow, cancel step 1 machine.cpp ac_2_1_cancel_returns_the_same_coins_not_just_their_value, ac_2_2_… Tested
FR-5 exact change make_change coins.cpp change_… tests, ac_1_5_…, ac_1_6_…, ac_1_7_… Tested
FR-6 a jam costs nothing order of steps in sell; Slot::jammed step 1 machine.cpp ac_1_8_a_jam_charges_nothing_and_puts_the_slot_out_of_order, ac_3_3_stocking_a_slot_again_clears_the_jam Tested
FR-7 the door Maintenance, open_door step 1 machine.cpp ac_3_1_…, ac_3_2_… Tested
FR-8 loading and taking coins load_coins, take_coins step 1 machine.cpp ac_3_4_the_operator_loads_and_takes_coins_only_with_the_door_open Tested
FR-9 card sale (change) AwaitingCard, choose_card, present_card step 2 machine.cpp ac_4_1_…, ac_4_2_…, ac_4_4_…, ac_4_7_… (step 2) Tested
FR-10 charged only if the item drops CardPayments, pay_by_card card_payments.hpp, step 2 machine.cpp ac_4_1_…, ac_4_3_…, an_unreachable_provider_…, a_motor_fault_after_authorizing_… (step 2) Tested
FR-11 coins or card, not both visits over AwaitingCard and HasCredit step 2 machine.cpp ac_4_5_…, ac_4_6_…, a_card_presented_when_none_was_asked_for_does_nothing (step 2) Tested
NFR-1 whole cents std::int64_t everywhere; prices checked coins.hpp, stock none beyond the price checks in ac_3_3_stocking_rejects_… Reviewed
NFR-2 every coin accounted for INV-1 step 1 machine.cpp inv_1_and_inv_2_every_coin_is_accounted_for Tested
NFR-3 hardware behind interfaces Dispenser, CardPayments dispenser.hpp, card_payments.hpp every test uses stand-ins Tested
NFR-4 answers at once small search; no I/O but the hardware calls coins.cpp none Not measured
INV-1 coins balance every coin-moving function step 1 machine.cpp inv_1_and_inv_2_every_coin_is_accounted_for Tested
INV-2 a sale adds its price sell step 1 machine.cpp inv_1_and_inv_2_…, ac_1_1_and_1_2_… Tested
INV-3 no open door with credit the State type; open_door machine.hpp, machine.cpp ac_3_1_…; ac_4_5_… (step 2) Tested
INV-4 a count falls only on a drop sell, pay_by_card both machine.cpp ac_1_4_…, ac_1_5_…, ac_1_8_…; ac_4_3_…, a_motor_fault_… (step 2) Tested
INV-5 credit means at least one coin insert creates HasCredit with one coin step 1 machine.cpp none: no function can empty HasCredit in place Reviewed

Exercise: A timeout for an abandoned card sale

A customer chooses “pay by card”, then walks away. The machine shows “PRESENT CARD 1.50” until someone presses cancel. The client asks for the card sale to end by itself after 30 seconds.

  1. The machine has no clock. Who should tell it the time, and how? (See how the parking lot study passes times in.)
  2. Which state gains data, and what data?
  3. Write a tick(now) function. What should it do in each of the four states? Should an abandoned HasCredit time out too?
  4. Which existing functions must change, and how does the compiler help you find them?
  5. Write the tests: just before 30 seconds, at 30 seconds, and a card presented after the timeout.
Show the explained answer
  1. The caller passes the time in, as the parking lot passes Time now: choose_card(slot, now) and tick(now), with a std::chrono::steady_clock::time_point or a test-friendly Time type. A test can then use any time, and the machine never reads a clock itself.

  2. AwaitingCard gains a deadline: struct AwaitingCard { std::string slot; Time deadline; };, set to now + 30s by choose_card.

  3. A sketch, not part of the example:

    IllustrativeA fragment for explanation; not compiled on its own.

    // Called by the owner with the current time. Only a card sale can time
    // out; every other state is returned as it is.
    void VendingMachine::tick(Time now) {
    state_ = std::visit(Overloaded{
    [](const Idle&) -> State { return Idle{}; },
    [](const HasCredit& s) -> State { return s; },
    [&](const AwaitingCard& s) -> State {
    // At or past the deadline: end the sale.
    // Nothing was reserved, so nothing to undo.
    if (now >= s.deadline) return Idle{};
    return s;
    },
    [](const Maintenance&) -> State { return Maintenance{}; },
    },
    state_);
    }

    HasCredit should not time out silently: the customer’s coins are inside, and returning them to the tray with nobody there, or keeping them, are both decisions for the client. Ask. Nothing is reserved on a card while waiting, so ending an AwaitingCard costs nothing.

  4. choose_card must set the deadline. If tick is written as a visit, the compiler insists on an answer for every state. Changing AwaitingCard from one member to two does not by itself break AwaitingCard{code}: aggregate initialization leaves the deadline value-initialized, which is the clock’s epoch, so the sale would time out at once. GCC and Clang both warn about the missing initializer under -Wextra (-Wmissing-field-initializers), and this project builds with -Werror, so here each place that builds an AwaitingCard is reported. Without those flags, give AwaitingCard a constructor that takes both, so a missing deadline cannot compile.

  5. Choose at 10:00:00. tick(10:00:29) leaves “PRESENT CARD 1.50”. tick(10:00:30) shows “INSERT COINS”. After that, present_card("card-1") returns no_card_sale and the fake provider’s log is empty: nothing was reserved. Pick >= or > for the boundary, write it in the requirement, and test exactly 30 seconds.

  • Most of a vending machine’s design comes from questions about money: what cancel returns, when change is impossible, and what a jam costs.
  • Credit is the inserted coins themselves, kept inside the HasCredit state. Cancel returns them, and a door-open state with credit cannot be written down.
  • Exact change from a limited box needs a search that can back off; largest-first alone refuses sales it could make.
  • Order a sale as plan, drop, then commit: a jam needs no undo.
  • A std::variant of small state structs, with every action a visit that returns the next state, fits a few states with a little behaviour each. Adding a state turns every place that must decide into a compile error.
  • Card payment is one more state and the same ordering: reserve, drop, then capture or cancel.
  • Expected outcomes are values; mistakes and hardware failures are exceptions that leave the machine as it was.