Walkthrough: coffee-shop ordering kiosk
What you will learn on this page
Section titled “What you will learn on this page”- How to turn a few sentences from a shop owner into questions, and how to tell the owner’s answers apart from your own assumptions.
- How each requirement choice forces some things and rules out others, before any code exists.
- How to compare two honest candidate designs, a class per drink with Decorator for the options and a menu held as plain data, and how to decide which one fits this shop.
- How a small C++ design keeps ownership and lifetime obvious: values, copies where they help, and pointers that never outlive what they point at.
- How acceptance criteria become test names, and how a later change (happy-hour prices) lands in a design that did not plan for it.
How to use this walkthrough
Section titled “How to use this walkthrough”The page is built as a series of stages, in the order a designer meets them. Each stage starts with a question for you. Stop and answer it, on paper or in your head, before you open the stage. Then compare. The point is not to match the answer word for word: at most stages, more than one answer is reasonable, and the stage says which parts are judgement.
Each stage opens with its “Show stage” button. It is a normal disclosure control: it works with the keyboard (Tab to it, then Enter or Space) and without JavaScript. Nothing is saved; the stages are closed again when you reload the page.
The code is the example examples/practice/walkthroughs/coffee-kiosk,
in two steps. Step 1 is the design chosen at stage 6. Step 2 is the
same program after the changed requirement in stage 8.
Stage 1: the problem statement
Section titled “Stage 1: the problem statement”Think first. Imagine the owner is about to describe what they want. What kinds of things will you listen for, and what will you write down?
Show stage 1: what the owner says
“We want a screen by the door where people order their own coffee. They pick a drink and a size, maybe oat milk or a syrup, and it shows them the price. Then the order goes to the bar, the baristas make it, and we call the number out when it’s ready. Nothing fancy. Oh, and it shouldn’t take orders for things we don’t make.”
Things worth writing down, because they are nouns and verbs you will need: drink, size, option (oat milk, syrup), price, order, bar, number, ready. And one rule: refuse what the shop does not make.
Things that are missing, because the owner does not think of them as decisions: which drinks come in which sizes, whether every option goes on every drink, how many drinks one order can hold, what happens when a customer taps something wrong, and what the stages of an order are between “placed” and “collected”. “Nothing fancy” is not a requirement; it is a hint that the owner wants something small, and a warning that they will not volunteer the details.
Stage 2: clarifying questions
Section titled “Stage 2: clarifying questions”Think first. Write five questions you would ask the owner before designing anything. For each, say why the answer would change the design. Then open the stage.
Show stage 2: the questions and the owner’s answers
In the table, Owner means the owner gave that answer. Assumption means the designer chose it and the owner did not object; an assumption is written down so that it can be checked later, as described in Assumptions.
| Question | Answer | Kind |
|---|---|---|
| Which drinks, in which sizes, at what price? | Espresso, small only, 2.50. Latte: small 3.50, medium 4.00, large 4.50. Tea: small 2.50, large 3.00. | Owner |
| Which options, on which drinks, for how much? | Oat milk 0.50, extra shot 0.70, vanilla syrup 0.40, caramel syrup 0.40. A latte can have any of them, an espresso only an extra shot, a tea only oat milk. | Owner |
| Does an option cost the same on every drink? | Yes. | Owner |
| Can a customer add the same option twice? | No. If the shop ever sells a double shot, it is its own button. | Owner |
| How many drinks can one order hold? | Up to 10 of the same drink on one line, and at most 20 drinks in an order, so one person cannot block the bar. | Owner |
| What happens when a customer taps something wrong? | The screen says what is wrong, and nothing is added. | Owner |
| If one line has several mistakes, which one is shown? | The first, in the order a person would notice: the drink, its size, its options, then how many. | Assumption |
| If the menu prices change, what about open orders? | A line keeps the price it was given when it was added. | Assumption, accepted |
| What are the stages of an order? | Placed, preparing, ready, collected. The bar moves an order on one stage at a time. | Owner |
| Can an order be cancelled? | Not on the kiosk for now; staff handle it at the till. | Owner |
| Does the kiosk take payment? | No. The card reader is a separate box; leave it out. | Owner |
| How many kiosks and bar screens? | One of each. | Owner |
| What if the kiosk restarts mid-shift? | Losing the open orders is acceptable for now. | Owner |
| What are order numbers like? | Short, to call out: they start at 1 and go up. After a restart they start at 1 again. | Owner, then a consequence |
| Is tax shown separately? | Not modelled: the board price is what the customer pays. | Assumption |
| Any discounts or offers? | Not now. | Owner |
| What is a sensible largest price? | 100.00 for one size or option, as a guard against a typo such as 450.00 for 4.50. The shop did not ask for it. | Assumption |
Two questions did most of the work. “Which options go on which drinks?” showed that an option is not allowed everywhere, so the design needs a place where that rule lives. “What happens when a customer taps something wrong?” showed that a refusal is an everyday outcome, not an error, which decides how the code reports it. For more on asking questions that change the design, see Clarification questions.
Stage 3: requirement choices
Section titled “Stage 3: requirement choices”Think first. From the answers, write two functional requirements and two non-functional ones. Then write one acceptance criterion precise enough that a test could check it.
Show stage 3: requirements and acceptance criteria
Functional requirements
- FR-1 Menu. The kiosk knows the drinks, the sizes each is sold in, the price of each size, the options each drink allows, and the price of each option.
- FR-2 Lines. A customer builds an order line by line: a drink, a size, a set of options, and a quantity. A line that breaks a rule is refused with a reason, and the order is unchanged.
- FR-3 Totals. The order shows a total: the line totals added up.
- FR-4 Queue. A placed order gets a number, and the bar moves it from placed to preparing to ready to collected.
Non-functional requirements
- NFR-1 Exact money. Prices add up exactly, to the cent, every time.
- NFR-2 Refusals explain themselves and change nothing. A refused line or move leaves everything as it was and carries a sentence for the screen. A menu set up wrong fails at start-up, not at the counter.
- NFR-3 Testable on a laptop. Every rule can be checked by a test with no screen, no card reader, and no bar.
- NFR-4 Small and local. One kiosk and one bar screen on one thread; orders in memory only.
Acceptance criteria. Each one is a test with the same number in its
name, so ac_2_5_a_line_has_1_to_10_drinks checks AC-2.5.
| AC | Criterion |
|---|---|
| AC-1.1 | The menu finds an item by its id (and not an unknown one), and knows each size and option price. |
| AC-1.2 | A menu set up wrong is refused when it is built: no items, an empty id or name, a repeated id, no sizes, a price out of range, or an allowed option with no price. |
| AC-2.1 | A line costs the size price plus the option prices, times the quantity. |
| AC-2.2 | An unknown item is refused. |
| AC-2.3 | A size the drink is not sold in is refused. |
| AC-2.4 | An option the drink does not allow is refused. |
| AC-2.5 | A line has 1 to 10 drinks. |
| AC-2.6 | An order holds at most 20 drinks. |
| AC-2.7 | When a line has several mistakes, the first is the one reported. |
| AC-3.1 | The total adds up the lines, and is 0.00 for an empty order. |
| AC-3.2 | An order keeps the price it was given, even after the menu is gone. |
| AC-4.1 | Placed orders get numbers from 1 and start as placed. |
| AC-4.2 | An empty order is refused without using up a number. |
| AC-4.3 | An order moves forward one step at a time. |
| AC-4.4 | Every other move (back, skip, stay, or move a collected order) is refused and changes nothing. |
| AC-4.5 | An unknown order number is refused. |
| AC-4.6 | The screens list orders by status, oldest first. |
| AC-4.7 | The queue keeps its own copy of a placed order. |
Notice what is not here: no requirement names a class, and none says “use a pattern”. Requirements describe behaviour; the design comes later and has to earn its shape from them.
Stage 4: consequences of those choices
Section titled “Stage 4: consequences of those choices”Think first. Pick two of the choices above. For each, what does it force the code to do, and what does it rule out?
Show stage 4: what each choice forces and rules out
| Choice | Forces | Rules out, or makes harder |
|---|---|---|
| Exact money (NFR-1) | Whole cents in an integer; a function to print “4.50”. | double prices, and any comparison that needs a tolerance. |
| A refused tap is ordinary (FR-2, NFR-2) | Refusals returned as values with a reason and a sentence; checks before any change. | Exceptions for customer mistakes. Exceptions stay for set-up mistakes, which are bugs. |
| Options are allowed per drink, priced per shop | One place that knows both the drink’s allowed options and the option prices. | Putting the option price inside each drink, which would let oat milk cost 0.50 in one drink and 0.60 in another. |
| No option twice | A set of options, not a list. | A “double oat milk” line; a double shot needs its own option. |
| Sizes and options are short, fixed lists | enum class for both, so a typo does not compile. |
Adding an option without rebuilding the program. The owner changes the menu boards a few times a year, so this is accepted. |
| A line keeps the price it was given | The line copies the name and prices when it is added. | Reading prices from the menu at total time, and lines that depend on the menu still existing. |
| One step forward at a time (FR-4) | One function that says which status comes next. | Cancelling, or a “remake” that goes back. Both would be new rules, not a tweak. |
| In memory, one thread (NFR-4) | No locks, no files, no database. Numbers restart at 1 after a restart. | A second kiosk, or surviving a restart, without a redesign of the queue. |
| Testable on a laptop (NFR-3) | The rules sit in plain classes and functions with no screen or device code. | Logic inside button handlers. |
The last row is easy to skip and expensive to miss. Once logic lives in a button handler, every test needs a screen. Keeping the rules in plain code is what makes the 18 tests in stage 7 possible.
Stage 5: candidate designs
Section titled “Stage 5: candidate designs”Think first. Sketch two different ways to represent “a large latte with oat milk and vanilla syrup” in C++. Which one makes “tea cannot have caramel syrup” easy to check?
Show stage 5: two candidates and their trade-offs
Candidate A: a class per drink, with Decorator for the options. This
is a well-known textbook shape. Each drink is a class with a virtual
cost, and each option is a class that wraps another drink, owns it,
and adds its own price.
IllustrativeA fragment for explanation; not compiled on its own.
// Candidate A: every drink and every option is a class.class Drink {public: virtual ~Drink() = default; [[nodiscard]] virtual std::string describe() const = 0; [[nodiscard]] virtual std::int64_t cost_cents() const = 0;};
class LargeLatte final : public Drink {public: [[nodiscard]] std::string describe() const override { return "large latte"; } [[nodiscard]] std::int64_t cost_cents() const override { return 450; }};
// An option wraps a drink and owns it: the wrapped drink lives as long as// the wrapper does.class OatMilk final : public Drink {public: explicit OatMilk(std::unique_ptr<Drink> inner) : inner_(std::move(inner)) {} [[nodiscard]] std::string describe() const override { return inner_->describe() + " + oat milk"; } [[nodiscard]] std::int64_t cost_cents() const override { return inner_->cost_cents() + 50; }
private: std::unique_ptr<Drink> inner_;};
// 4.50 + 0.50 = 5.00. Nothing stops OatMilk(OatMilk(...)), or oat milk// on a drink the shop does not allow it on.const std::unique_ptr<Drink> drink = std::make_unique<OatMilk>(std::make_unique<LargeLatte>());This sketch was compiled and run on its own (with its includes and a
main); it is not part of the example.
What candidate A gives: adding an option is adding a class, and no
existing class changes. Ownership is clear, because each wrapper owns
the drink inside it through a std::unique_ptr.
What it costs here:
- The rules the owner cares about are not in the types. The type system happily builds oat milk on oat milk, or caramel syrup on tea. Both need a check at run time anyway, and that check has to know which drink is inside a stack of wrappers.
- The prices are in the code. A price change is a rebuild, and the option prices are spread over one class each.
- Size multiplies classes, or becomes a field that every drink class has to handle.
- An order is awkward to copy. A line holds a chain of
unique_ptrs, so copying an order (stage 6 needs that) means adding a virtualcloneto every class.
Candidate B: the menu as data, and one pricing function. A drink is
a MenuItem: an id, a name, a map from size to price, and a set of
allowed options. Option prices are one shared map. One function,
price_line, checks a requested line against the menu and prices it.
An order is a vector of priced lines, held by value.
What candidate B gives: every rule from stage 2 lives in one function
that reads the menu. “Tea cannot have caramel syrup” is a look-up in a
set. A price change is a data change. Lines are plain values, so an
order copies like an int does.
What it costs: adding a kind of option that behaves differently (not
just costs differently) would mean changing price_line, and the
enum class lists mean a new option is a rebuild.
| Question | A: classes and Decorator | B: data and one function |
|---|---|---|
| Where is “option not allowed” checked? | Outside the classes, by looking inside wrappers | In price_line, a set look-up |
| A price changes | Edit a class, rebuild | Edit the menu data |
| A new option with only a price | A new class | An enum value and a price |
| A new option that changes how a drink is made | A new class; the others do not change | A change to the pricing code |
| Copy an order | Needs clone on every class |
Free: lines are values |
| Test the rules | Build wrapper stacks | Build a menu, call one function |
Why B fits here. The owner’s options differ only in price and in where they are allowed. Both are data. A hierarchy would add classes to express things that a map and a set already say, and would still need the run-time checks.
When A would be the better choice. If options had behaviour of their own, such as each one sending its own steps to a drinks machine, or if new options had to be added by other teams without changing the pricing code, then a wrapper per option starts to earn its classes. Decorator describes that shape properly, and Pattern or no pattern gives the general test. Naming a pattern does not settle the question in either direction: what settles it is whether the varying part is data or behaviour.
Stage 6: the chosen design
Section titled “Stage 6: the chosen design”Think first. Before opening: which object should own the menu items, which should own the lines of an order, and what should an order line hold so that the order does not depend on the menu staying alive?
Show stage 6: classes, a sequence, the code, and its lifetimes
The types. Three small classes (Menu, Order, OrderQueue), a
handful of plain structs, and one free function. No interface, no
virtual function, and no pattern.
Text description of the diagram
Menuowns a vector ofMenuItemand a map from eachOptionto its price.findreturns aconst MenuItem*that does not own anything;price_ofreturns an option’s price.MenuItemis plain data: an id, a name, a map fromSizeto price, and a set of allowed options.LineRequestis what the screen sends: an item id, a size, a set of options, and a quantity.OrderLineowns a copy of itsLineRequest, plus a copied name, unit price, and line total.Orderowns a vector ofOrderLineand hasadd,drink_count, andtotal.OrderQueueowns a map from order number toPlacedOrderand the next number to give out. It hasplace,advance,find, andnumbers_in.PlacedOrderowns anOrderand holds its number and status.Rejectionis aProblemand a sentence.- The free function
price_linereads aMenuand returns either anOrderLineor aRejection.Order::addcalls it.
Diagram source (Mermaid)
classDiagram
class Menu {
-vector~MenuItem~ items_
-map~Option, Money~ option_prices_
+find(string_view id) MenuItem pointer
+price_of(Option) Money
}
class MenuItem {
+string id
+string name
+map~Size, Money~ prices
+set~Option~ options
}
class LineRequest {
+string item_id
+Size size
+set~Option~ options
+int quantity
}
class OrderLine {
+LineRequest request
+string name
+Money unit_price
+Money line_total
}
class Order {
-vector~OrderLine~ lines_
+add(const Menu&, const LineRequest&) optional~Rejection~
+drink_count() int
+total() Money
}
class OrderQueue {
-map~OrderNumber, PlacedOrder~ orders_
-OrderNumber next_number_
+place(Order) PlaceResult
+advance(OrderNumber, Status) optional~Rejection~
+find(OrderNumber) PlacedOrder pointer
+numbers_in(Status) vector~OrderNumber~
}
class PlacedOrder {
+OrderNumber number
+Order order
+Status status
}
class Rejection {
+Problem problem
+string detail
}
class PricingFunctions {
<<free functions>>
+price_line(const Menu&, const LineRequest&) LineResult
}
Menu *-- MenuItem : items
Order *-- OrderLine : lines
OrderLine *-- LineRequest : request
OrderQueue *-- PlacedOrder : orders
PlacedOrder *-- Order : order
Order ..> PricingFunctions : add calls
PricingFunctions ..> Menu : reads
PricingFunctions ..> Rejection : may returnPlacing an order, as a sequence. The kiosk screen is not part of the example; the demo plays its part.
Text description of the diagram
- The kiosk screen calls
Order::addwith the menu and the request. addcallsprice_line, which asks the menu tofindthe item by id and gets back a pointer, or a null pointer for an unknown item.- If the item, size, options, and quantity pass,
price_lineasks the menu for each option’s price and returns a pricedOrderLine; otherwise it returns aRejection. - If the result is a
Rejection, or the line would take the order over 20 drinks,addreturns theRejectionand the order is unchanged. Otherwiseaddappends the line and returns an empty optional. - The screen hands the order to
OrderQueue::placewithstd::move. An empty order is refused and uses no number. Otherwise the queue stores aPlacedOrderunder the next number and returns that number. - The bar screen calls
advancewith the number and the next status. It gets an empty optional on success, or aRejectionfor an unknown number or a move that is not one step forward.
Diagram source (Mermaid)
sequenceDiagram
participant Screen as Kiosk screen
participant Order
participant Pricing as price_line
participant Menu
participant Queue as OrderQueue
participant Bar as Bar screen
Screen->>Order: add(menu, request)
Order->>Pricing: price_line(menu, request)
Pricing->>Menu: find(item_id)
Menu-->>Pricing: const MenuItem* or nullptr
Pricing->>Menu: price_of(option), for each option
Pricing-->>Order: OrderLine, or Rejection
alt Rejection, or over 20 drinks
Order-->>Screen: Rejection (order unchanged)
else accepted
Order->>Order: push_back(line)
Order-->>Screen: nullopt
end
Screen->>Queue: place(std::move(order))
alt order is empty
Queue-->>Screen: Rejection empty_order (no number used)
else
Queue->>Queue: store PlacedOrder with the next number
Queue-->>Screen: order number
end
Bar->>Queue: advance(number, preparing)
Queue-->>Bar: nullopt, or Rejection step_not_allowedMoney. Every price is a whole number of cents in an int64_t. The
operators are the ones a till needs, and nothing else.
VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// A price in cents. Never a double: 0.1 + 0.2 is not exactly 0.3 in binary// floating point, and a till that is out by a cent at the end of the day is// a bug someone has to explain. Whole cents add and multiply exactly.struct Money { std::int64_t cents = 0;
// "= default" compares the cents, so two prices are equal when their // cents are, and < means "cheaper than". friend constexpr auto operator<=>(const Money&, const Money&) = default; friend constexpr Money operator+(Money a, Money b) { return {a.cents + b.cents}; } friend constexpr Money operator-(Money a, Money b) { return {a.cents - b.cents}; } // A unit price times a quantity, for example 4.50 * 3 = 13.50. friend constexpr Money operator*(Money price, int count) { return {price.cents * count}; } constexpr Money& operator+=(Money other) { cents += other.cents; return *this; }};
[[nodiscard]] constexpr Money cents(std::int64_t count) { return {count}; }
// "4.50", or "-0.90" for a negative amount.[[nodiscard]] inline std::string to_string(Money money) { const std::int64_t magnitude = money.cents < 0 ? -money.cents : money.cents; std::string fraction = std::to_string(magnitude % 100); if (fraction.size() < 2) fraction.insert(0, "0"); // 5 cents is ".05", not ".5" return (money.cents < 0 ? "-" : "") + std::to_string(magnitude / 100) + "." + fraction;}Refusals. One enum lists every reason the kiosk can say no, and a
Rejection pairs it with a sentence for the screen. Code checks the
problem; people read the detail.
VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// Every reason the kiosk can say no. A refusal is an ordinary outcome here// (customers tap the wrong thing all the time), so it is returned as a value// the screen can show, not thrown. Exceptions are kept for set-up mistakes,// such as a menu with a missing price, which are bugs, not customer errors.enum class Problem { unknown_item, // the item id is not on the menu size_not_offered, // the drink is not sold in that size option_not_allowed, // that option cannot go on that drink quantity_out_of_range, // a line must have 1 to 10 drinks order_too_large, // an order may hold at most 20 drinks empty_order, // an order with no lines cannot be placed unknown_order, // no placed order has that number step_not_allowed, // an order moves forward one status at a time};
// What was refused and why: the reason for code to check, the detail for// a person to read.struct Rejection { Problem problem; std::string detail;};
[[nodiscard]] inline std::string_view to_string(Problem problem) { switch (problem) { case Problem::unknown_item: return "unknown item"; case Problem::size_not_offered: return "size not offered"; case Problem::option_not_allowed: return "option not allowed"; case Problem::quantity_out_of_range: return "quantity out of range"; case Problem::order_too_large: return "order too large"; case Problem::empty_order: return "empty order"; case Problem::unknown_order: return "unknown order"; case Problem::step_not_allowed: return "step not allowed"; } return "?"; // not reached: every enumerator is handled above}The menu. Sizes and options are enum class lists. A MenuItem is
plain data. The Menu constructor checks everything once and throws
std::invalid_argument for a set-up mistake: that is a bug in the shop’s
configuration, found at start-up, not a customer error.
VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// The sizes and options are closed lists that change only when the shop// changes its menu boards, so they are enums, not strings: a typo such as// "lrage" fails to compile instead of failing at the counter.enum class Size { small, medium, large };enum class Option { oat_milk, extra_shot, vanilla_syrup, caramel_syrup };
[[nodiscard]] std::string_view to_string(Size size);[[nodiscard]] std::string_view to_string(Option option);
// One drink on the menu. Plain data: the Menu checks it once, when the// menu is built, and nothing changes it afterwards.struct MenuItem { std::string id; // what the screen sends, for example "latte" std::string name; // what the screen shows, for example "Latte" std::map<Size, Money> prices; // the sizes sold; a size not listed is not offered std::set<Option> options; // the options this drink may have};
// The largest price one size or option may have, 100.00. It is a guard// against a typo in the menu file (45000 cents instead of 450), not a rule// the shop asked for.inline constexpr Money max_price = cents(10'000);
// The drinks the kiosk sells and what each option costs. Option prices are// shared by every drink (oat milk costs the same in a latte and a tea).class Menu {public: // Throws std::invalid_argument if there are no items; an item has an // empty id or name, a repeated id, no sizes, or a size price that is // not between 0.01 and max_price; an allowed option has no price; or an // option price is not between 0.00 and max_price (an option may be free). Menu(std::vector<MenuItem> items, std::map<Option, Money> option_prices);
// The item with this id, or nullptr if it is not on the menu. The // pointer stays valid as long as this Menu exists and is not assigned // a new value: nothing else adds or removes an item. [[nodiscard]] const MenuItem* find(std::string_view id) const;
// The price of an option. Throws std::out_of_range if it has none, which // the constructor rules out for every option some item allows. [[nodiscard]] Money price_of(Option option) const { return option_prices_.at(option); }
[[nodiscard]] const std::vector<MenuItem>& items() const { return items_; }
private: std::vector<MenuItem> items_; std::map<Option, Money> option_prices_;};Lines and orders. LineRequest is what the customer asked for.
OrderLine is a request that passed every check, with its prices copied
in. LineResult is either one or a Rejection.
VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// Limits the shop chose when asked "how many drinks can one order hold?":// a line has 1 to 10 of the same drink, and an order at most 20 drinks in// all, so one person cannot block the bar with a 200-drink order.inline constexpr int max_quantity_per_line = 10;inline constexpr int max_drinks_per_order = 20;
// What the customer asked for on one line of the screen. options is a set,// so an option can appear at most once and the type itself rules out// "oat milk, oat milk" (a double shot would be its own option).struct LineRequest { std::string item_id; Size size = Size::medium; std::set<Option> options; int quantity = 1;};
// A line that passed every check, priced from the menu when it was added.// The name and prices are copied, not pointed at: an order does not need// the Menu to stay alive, and a later menu change does not reprice it.struct OrderLine { LineRequest request; std::string name; Money unit_price; // the size's price plus each option's price Money line_total; // unit_price * quantity};
// Either the priced line or why the request was refused.using LineResult = std::variant<OrderLine, Rejection>;
// The one place a line is checked against the menu and priced. It refuses// an unknown item, a size the item is not sold in, an option the item does// not allow, and a quantity outside 1 to max_quantity_per_line. It does not// know about the rest of the order; Order::add checks the order's limit.[[nodiscard]] LineResult price_line(const Menu& menu, const LineRequest& request);
// An order being built on the kiosk screen, line by line. It is a value:// copying it copies the lines, and it holds no pointer into the Menu.class Order {public: // Prices the request with price_line and adds it, or returns why not: // any refusal from price_line, or order_too_large if the order would go // over max_drinks_per_order. A refused line leaves the order unchanged. std::optional<Rejection> add(const Menu& menu, const LineRequest& request);
[[nodiscard]] const std::vector<OrderLine>& lines() const { return lines_; } [[nodiscard]] bool empty() const { return lines_.empty(); } [[nodiscard]] int drink_count() const; // the quantities added up [[nodiscard]] Money total() const; // the line totals added up; 0.00 when empty
private: std::vector<OrderLine> lines_;};The one check and pricing point.
VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// Each check returns early with its own reason, in the order a person// would notice the mistake: the drink, then its size, its options, and// how many. Only a request that passes them all is priced.LineResult price_line(const Menu& menu, const LineRequest& request) { const MenuItem* item = menu.find(request.item_id); if (item == nullptr) { return Rejection{Problem::unknown_item, "no item '" + request.item_id + "' on the menu"}; } // find returns an iterator to the size's price, or end() if it is not sold. const auto size_price = item->prices.find(request.size); if (size_price == item->prices.end()) { return Rejection{Problem::size_not_offered, item->name + " is not sold in " + std::string(to_string(request.size))}; } for (const Option option : request.options) { if (!item->options.contains(option)) { return Rejection{Problem::option_not_allowed, item->name + " cannot have " + std::string(to_string(option))}; } } if (request.quantity < 1 || request.quantity > max_quantity_per_line) { return Rejection{Problem::quantity_out_of_range, "a line has 1 to " + std::to_string(max_quantity_per_line) + " drinks"}; } // size_price->second is the price stored for that size. Money unit_price = size_price->second; for (const Option option : request.options) unit_price += menu.price_of(option); return OrderLine{request, item->name, unit_price, unit_price * request.quantity};}How this code works: price_line on two requests from the demo
2 × large latte with oat milk and vanilla syrup. find("latte")
returns the latte. The latte is sold in large, at 4.50. Both options are
in its allowed set. The quantity, 2, is within 1 to 10. So the unit
price is 4.50 + 0.50 + 0.40 = 5.40, and the line total is 5.40 × 2 =
10.80.
1 × large tea with caramel syrup. find("tea") returns the tea. It
is sold in large. Caramel syrup is not in the tea’s allowed set, so the
loop over the options returns option_not_allowed with the sentence
“Tea cannot have caramel syrup”. The quantity is never looked at.
The order of the four checks is the answer to “which mistake is shown?”
from stage 2. A request for a large espresso with a quantity of 0 is
refused as size_not_offered, not quantity_out_of_range; test AC-2.7
checks exactly that.
price_line does not know about the rest of the order, so it cannot
check the 20-drink limit. That is Order::add’s job, below.
VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
std::optional<Rejection> Order::add(const Menu& menu, const LineRequest& request) { LineResult result = price_line(menu, request); // get_if gives a pointer to the Rejection if that is what the variant // holds, and nullptr otherwise. if (const auto* rejection = std::get_if<Rejection>(&result)) return *rejection; if (drink_count() + request.quantity > max_drinks_per_order) { return Rejection{Problem::order_too_large, "an order holds at most " + std::to_string(max_drinks_per_order) + " drinks"}; } // Only now is the order changed, so every refusal above leaves it as it was. lines_.push_back(std::get<OrderLine>(std::move(result))); return std::nullopt;}add checks first and changes last. Every return above the
push_back leaves lines_ exactly as it was, which is what NFR-2 asks
for. The test helper refusal_of checks it after every refusal: it
compares the number of lines and the total before and after.
The queue. An order moves only forward, one status at a time. The
rule for “what comes next” is one small function, next_after, in
order_queue.cpp.
VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// Where a placed order is. It only ever moves forward, one step at a time:// placed -> preparing -> ready -> collected.enum class Status { placed, preparing, ready, collected };
[[nodiscard]] std::string_view to_string(Status status);
// The number printed on the receipt and called out at the counter.using OrderNumber = int;
// An order the queue has accepted, with its number and where it is now.struct PlacedOrder { OrderNumber number = 0; Order order; Status status = Status::placed;};
// Either the number the new order was given or why it was refused.using PlaceResult = std::variant<OrderNumber, Rejection>;
// The orders waiting for, being made by, or ready from the bar. In memory// only: if the kiosk restarts, the queue is lost (the shop said that is// acceptable for now). Single-threaded: one kiosk and one bar screen// calling from the same thread.class OrderQueue {public: // Takes the order by value, so the queue owns its own copy (pass // std::move(order) to hand it over without copying). Refuses an empty // order with empty_order. Numbers start at 1 and go up by one for each // order accepted; a refused order does not use up a number. PlaceResult place(Order order);
// Moves the order to `to`, which must be the status straight after its // current one. Refuses an unknown number (unknown_order) and any other // move (step_not_allowed): skipping a step, going back, staying put, // or moving a collected order. A refusal changes nothing. std::optional<Rejection> advance(OrderNumber number, Status to);
// The order with this number, or nullptr. Map entries never move and // the queue never erases one, so the pointer stays valid as long as // this queue exists and is not assigned a new value. [[nodiscard]] const PlacedOrder* find(OrderNumber number) const;
// The numbers of the orders in a status, oldest first: what the bar // screen shows under "to make" and the counter screen under "ready". [[nodiscard]] std::vector<OrderNumber> numbers_in(Status status) const;
private: // Keyed by number. Numbers only go up, so the map's order (smallest key // first) is also the order the orders were placed in. std::map<OrderNumber, PlacedOrder> orders_; OrderNumber next_number_ = 1;};VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
PlaceResult OrderQueue::place(Order order) { if (order.empty()) return Rejection{Problem::empty_order, "add a drink first"}; const OrderNumber number = next_number_++; // use this number, then move the counter on orders_.emplace(number, PlacedOrder{number, std::move(order), Status::placed}); return number;}VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
std::optional<Rejection> OrderQueue::advance(OrderNumber number, Status to) { const auto found = orders_.find(number); if (found == orders_.end()) { return Rejection{Problem::unknown_order, "no order " + std::to_string(number)}; } PlacedOrder& placed = found->second; // a reference: the change below is to the stored order if (next_after(placed.status) != to) { // An empty optional never equals a value, so for a collected order // the != is true and the move is refused here too. return Rejection{Problem::step_not_allowed, "order " + std::to_string(number) + " is " + std::string(to_string(placed.status)) + ", cannot become " + std::string(to_string(to))}; } placed.status = to; return std::nullopt;}How this code works: OrderQueue::advance
advance first finds the order. An unknown number is refused with
unknown_order. Then it compares the requested status with
next_after(current). For a placed order that is preparing; for a
collected order it is an empty std::optional. An empty optional never
equals a status, so every move of a collected order is refused by the
same comparison, without a special case.
placed is a reference to the order stored in the map, so the one
assignment at the end changes the stored order. Nothing is assigned
before the checks pass, so a refused move changes nothing (AC-4.4).
The state diagram for an order is a straight line of four states. The state diagrams lesson shows how to draw and test richer ones.
Ownership and lifetime
- The menu owns its items. The constructor takes the vector and the map by value and moves them into the members. Nothing the caller does afterwards can change the menu.
findreturns a non-owning pointer into the menu’s vector. It is valid as long as the menu exists and is not assigned a new value, because the menu has no function that adds or removes an item, so the vector never reallocates.price_lineuses the pointer only during the call.- An order owns its lines by value, and a line owns copies of the name and prices. An order holds no pointer or reference into the menu, so it can outlive the menu (AC-3.2 destroys the menu, then reads the order), and a later menu change does not reprice it.
Order::addborrows the menu (const Menu&) only for the call. It does not store it.- The queue takes an order by value. Pass
std::move(order)to hand it over without a copy, or pass the order itself to give the queue a copy and keep yours (AC-4.7). OrderQueue::findreturns a pointer into astd::map. Map entries do not move when others are added, and the queue never erases one, so the pointer is valid as long as the queue is.- There is no
new, nodelete, and noshared_ptr. Every class follows the rule of zero: the compiler-written copy, move, and destructor are correct because every member is a value.
Stage 7: tests
Section titled “Stage 7: tests”Think first. Pick AC-2.6 (“an order holds at most 20 drinks”). What inputs would you test, and what would you check besides “it was refused”?
Show stage 7: how the criteria map to tests, and a real run
Each acceptance criterion from stage 3 is one test, named after it:
ac_1_1_… to ac_4_7_…, 18 tests in all. A failing test name points
straight at the criterion it breaks. The line tests, which cover
AC-2.1 to AC-2.7:
VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
LLD_TEST(ac_2_1_a_line_costs_the_size_price_plus_options_times_quantity) { const Menu menu = test_menu(); Order order; // (4.50 + 0.50 oat milk + 0.40 vanilla) * 2 = 10.80 LLD_CHECK( !order.add(menu, {"latte", Size::large, {Option::oat_milk, Option::vanilla_syrup}, 2})); LLD_CHECK_EQ(order.lines().size(), std::size_t{1}); const OrderLine& line = order.lines().front(); LLD_CHECK_EQ(line.name, std::string("Latte")); LLD_CHECK_EQ(line.unit_price, cents(540)); LLD_CHECK_EQ(line.line_total, cents(1080)); // No options: the size price alone. LLD_CHECK(!order.add(menu, {"latte", Size::small, {}, 1})); LLD_CHECK_EQ(order.lines().back().line_total, cents(350));}
LLD_TEST(ac_2_2_an_unknown_item_is_refused) { const Menu menu = test_menu(); Order order; LLD_CHECK_EQ(refusal_of(order, menu, {"mocha", Size::medium, {}, 1}), std::optional{Problem::unknown_item}); LLD_CHECK_EQ(refusal_of(order, menu, {"Latte", Size::medium, {}, 1}), std::optional{Problem::unknown_item}); // ids are exact, case included}
LLD_TEST(ac_2_3_a_size_the_drink_is_not_sold_in_is_refused) { const Menu menu = test_menu(); Order order; LLD_CHECK_EQ(refusal_of(order, menu, {"espresso", Size::large, {}, 1}), std::optional{Problem::size_not_offered}); LLD_CHECK_EQ(refusal_of(order, menu, {"tea", Size::medium, {}, 1}), std::optional{Problem::size_not_offered});}
LLD_TEST(ac_2_4_an_option_the_drink_does_not_allow_is_refused) { const Menu menu = test_menu(); Order order; LLD_CHECK_EQ(refusal_of(order, menu, {"tea", Size::small, {Option::caramel_syrup}, 1}), std::optional{Problem::option_not_allowed}); // One allowed option does not excuse a second one that is not allowed. LLD_CHECK_EQ(refusal_of(order, menu, {"tea", Size::small, {Option::oat_milk, Option::extra_shot}, 1}), std::optional{Problem::option_not_allowed}); LLD_CHECK_EQ(refusal_of(order, menu, {"tea", Size::small, {Option::oat_milk}, 1}), std::optional<Problem>{});}
LLD_TEST(ac_2_5_a_line_has_1_to_10_drinks) { const Menu menu = test_menu(); Order order; for (const int bad : {0, -1, max_quantity_per_line + 1}) { LLD_CHECK_EQ(refusal_of(order, menu, {"tea", Size::small, {}, bad}), std::optional{Problem::quantity_out_of_range}); } LLD_CHECK_EQ(refusal_of(order, menu, {"tea", Size::small, {}, 1}), std::optional<Problem>{}); LLD_CHECK_EQ(refusal_of(order, menu, {"tea", Size::small, {}, max_quantity_per_line}), std::optional<Problem>{}); LLD_CHECK_EQ(order.drink_count(), 11);}
LLD_TEST(ac_2_6_an_order_holds_at_most_20_drinks) { const Menu menu = test_menu(); Order order; LLD_CHECK(!order.add(menu, {"tea", Size::small, {}, 10})); LLD_CHECK(!order.add(menu, {"tea", Size::large, {}, 9})); LLD_CHECK_EQ(refusal_of(order, menu, {"latte", Size::small, {}, 2}), std::optional{Problem::order_too_large}); LLD_CHECK_EQ(refusal_of(order, menu, {"latte", Size::small, {}, 1}), std::optional<Problem>{}); LLD_CHECK_EQ(order.drink_count(), max_drinks_per_order); LLD_CHECK_EQ(refusal_of(order, menu, {"latte", Size::small, {}, 1}), std::optional{Problem::order_too_large});}
LLD_TEST(ac_2_7_the_first_mistake_in_a_line_is_the_one_reported) { const Menu menu = test_menu(); Order order; // Wrong size and a quantity of zero: the size is reported. LLD_CHECK_EQ(refusal_of(order, menu, {"espresso", Size::large, {}, 0}), std::optional{Problem::size_not_offered}); // A forbidden option and a quantity of eleven: the option is reported. LLD_CHECK_EQ(refusal_of(order, menu, {"tea", Size::small, {Option::extra_shot}, 11}), std::optional{Problem::option_not_allowed});}Three things to notice:
- The edges are tested, not just a typical value. AC-2.5 refuses 0, −1, and 11 drinks on a line and accepts 1 and 10. AC-2.6 builds an order of 19 drinks, refuses a line of 2, accepts a line of 1 to reach exactly 20, and then refuses one more.
- Every refusal also checks that nothing changed.
refusal_ofcompares the order’s lines and total before and after, and checks that the sentence is not empty. - The order of the checks is tested on purpose (AC-2.7), because the stage 2 answer made it a requirement.
The other tests follow the same idea for the menu (AC-1.1 and AC-1.2, including the allowed edges: a free option, and prices of exactly 0.01 and 100.00) and for the queue (AC-4.1 to AC-4.7, including every refused move from every status).
The demo. step-1/main.cpp builds the demo order: three lines are
accepted and four are refused. It then places the order and moves it to
collected, trying an empty order, a skipped step, a second collection,
and an unknown number on the way. This is its real output, which the
build checks against expected_output.txt:
Add 2 x large latte + oat milk + vanilla syrup: 5.40 each, 10.80Add 1 x small espresso + extra shot: 3.20 each, 3.20Add 1 x medium mocha: refused, unknown item (no item 'mocha' on the menu)Add 1 x large espresso: refused, size not offered (Espresso is not sold in large)Add 1 x large tea + caramel syrup: refused, option not allowed (Tea cannot have caramel syrup)Add 11 x small tea: refused, quantity out of range (a line has 1 to 10 drinks)Add 3 x small tea: 2.50 each, 7.50Total: 21.50 for 6 drinksPlace an empty order: refused, empty orderPlaced as order 1Order 1 -> ready: refused, order 1 is placed, cannot become readyOrder 1 -> preparing: okOrder 1 -> ready: okReady screen shows: 1Order 1 -> collected: okOrder 1 -> collected: refused, order 1 is collected, cannot become collectedOrder 7 -> preparing: refused, no order 7Read it against the rules: 10.80 + 3.20 + 7.50 = 21.50, for 2 + 1 + 3 = 6 drinks. The refused lines (mocha, a large espresso, caramel syrup in tea, 11 teas) add nothing to the total. Each refusal shows its reason and its sentence.
What was run. Both steps’ tests and demos pass on the gcc-debug, clang-debug, and asan-ubsan build presets. The tsan preset builds the code but runs none of its tests, because the code is single-threaded.
Stage 8: a changed requirement
Section titled “Stage 8: a changed requirement”Think first. The owner comes back: “Can we do happy hour? 20% off large drinks from four to six.” Before opening, list what you would ask, and guess which parts of step 1 will have to change.
Show stage 8: happy hour, with an injected clock (step 2)
The new questions.
| Question | Answer | Kind |
|---|---|---|
| Are options discounted too? | Yes: 20% off the whole line, options included. | Owner |
| Is an order placed at exactly 18:00 in happy hour? | No. The window includes 16:00 and stops before 18:00. | Owner |
| Can two promotions apply at once? | They never add up. The biggest percent wins; on a tie, the one listed first. | Owner, then assumption for ties |
| Can a promotion run past midnight? | No: the shop closes before midnight, so a window must end after it starts on the same day. | Owner |
| How is 20% of an odd amount rounded? | To the nearest cent, a half cent rounding up, once per line. | Assumption, accepted |
| If happy hour ends while the drinks are being made? | The price is fixed when the order is placed. | Owner |
Why a clock has to be injected. The price now depends on the time,
and the most important tests are at the edges: 15:59, 16:00, 17:59,
18:00. A test cannot wait for 18:00, and a test that reads the real time
passes only at certain hours. So the queue asks a Clock for the time
instead of the operating system, and the tests and the demo use a
ManualClock they can set. This is
dependency injection used for the
one thing that needs it; ManualClock is a fake in the sense of
Test doubles and seams.
VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// A time of day to the minute: 0 is 00:00, 1439 is 23:59. The shop opens// and closes on the same day, so a promotion never runs past midnight and// a date is not needed.struct TimeOfDay { int minutes = 0;
friend constexpr auto operator<=>(const TimeOfDay&, const TimeOfDay&) = default;};
inline constexpr int minutes_per_day = 24 * 60;
// at(16, 30) is 16:30. Throws std::invalid_argument for a time that does// not exist, such as at(24, 0) or at(9, 60).[[nodiscard]] inline TimeOfDay at(int hour, int minute) { if (hour < 0 || hour > 23 || minute < 0 || minute > 59) { throw std::invalid_argument("no such time of day"); } return {hour * 60 + minute};}
// "09:05".[[nodiscard]] inline std::string to_string(TimeOfDay time) { const auto two_digits = [](int value) { return (value < 10 ? "0" : "") + std::to_string(value); }; return two_digits(time.minutes / 60) + ":" + two_digits(time.minutes % 60);}
// Where "now" comes from. The queue asks a Clock instead of reading the// system time itself, so a test can say "it is 17:59" and then "it is// 18:00" and check the price on each side of a promotion's end, without// waiting and without a test that passes only at certain hours.class Clock {public: virtual ~Clock() = default; [[nodiscard]] virtual TimeOfDay now() const = 0;};
// A clock that says whatever it was last set to. Used by the tests and the// demo. A real kiosk would add a SystemClock whose now() reads the local// time; it is left out here because nothing in this example could test it.class ManualClock final : public Clock {public: explicit ManualClock(TimeOfDay start) : now_(start) {} [[nodiscard]] TimeOfDay now() const override { return now_; } void set(TimeOfDay time) { now_ = time; }
private: TimeOfDay now_;};The single rounding point. A discount is the one step that cannot be exact in cents, so it happens in one function.
VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// The rounding rule, in the one place a discount is worked out: percent// of amount, rounded to the nearest cent, a half cent rounding up. 25% of// 4.50 is 1.125, so 1.13 off; 15% of 4.55 is 0.6825, so 0.68 off.// Adding 50 before dividing by 100 is what turns "round down" into// "round to nearest, half up". Expects amount >= 0 and 0 <= percent <= 100.[[nodiscard]] constexpr Money percent_off(Money amount, int percent) { return {(amount.cents * percent + 50) / 100};}Promotions and quotes.
VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// A time-boxed discount on every drink of one size, options included. The// window includes its start and excludes its end: 16:00 to 18:00 covers// 16:00 up to 17:59, and an order placed at 18:00 pays full price.struct Promotion { std::string name; Size size = Size::large; int percent = 0; // 1 to 100 TimeOfDay starts; TimeOfDay ends;};
// The promotions the shop is running. Checked once, when built, and never// changed afterwards, so a pointer from best_for stays valid as long as// this object exists and is not assigned a new value.class Promotions {public: Promotions() = default; // no promotions: everything at menu price
// Throws std::invalid_argument if a promotion has an empty name, a // percent outside 1 to 100, a time outside the day, or a window that // does not end after it starts. explicit Promotions(std::vector<Promotion> promotions);
// The promotion for a line of this size at this time, or nullptr if // none applies. Promotions never add up: if two apply, the bigger // percent wins, and on a tie the one listed first. [[nodiscard]] const Promotion* best_for(Size size, TimeOfDay time) const;
private: std::vector<Promotion> promotions_;};VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
const Promotion* Promotions::best_for(Size size, TimeOfDay time) const { const Promotion* best = nullptr; for (const Promotion& promotion : promotions_) { // Half-open window: the start minute counts, the end minute does not. const bool running = promotion.starts <= time && time < promotion.ends; if (!running || promotion.size != size) continue; // Strictly greater, so on a tie the one found first is kept. if (best == nullptr || promotion.percent > best->percent) best = &promotion; } return best;}VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// One line of an order with its discount, if any.struct QuotedLine { OrderLine line; std::optional<std::string> promotion; // the name of the promotion used, if any Money discount; // percent_off(line.line_total, percent), or 0.00 Money total; // line.line_total - discount};
// What the customer pays for an order at a given time.struct Quote { std::vector<QuotedLine> lines; Money subtotal; // the line totals before discounts (Order::subtotal()) Money discount; // the line discounts added up Money total; // subtotal - discount};
// Prices the order as it would be at `time`. Each line gets at most one// promotion, and its discount is rounded once, on the whole line// (unit price times quantity), by percent_off. Rounding each drink instead// would give a different answer: three drinks of 4.50 at 25% are 3.38 off// as one line, but 1.13 * 3 = 3.39 off drink by drink.[[nodiscard]] Quote quote(const Order& order, const Promotions& promotions, TimeOfDay time);VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
Quote quote(const Order& order, const Promotions& promotions, TimeOfDay time) { Quote result; for (const OrderLine& line : order.lines()) { QuotedLine quoted{line, std::nullopt, Money{}, line.line_total}; if (const Promotion* promotion = promotions.best_for(line.request.size, time)) { quoted.promotion = promotion->name; quoted.discount = percent_off(line.line_total, promotion->percent); quoted.total = line.line_total - quoted.discount; } result.subtotal += line.line_total; result.discount += quoted.discount; result.lines.push_back(std::move(quoted)); } // Each line's total is its subtotal minus its discount, so this also // equals the line totals added up: nothing is rounded a second time. result.total = result.subtotal - result.discount; return result;}How this code works: quote on the step 2 demo order at 16:00
The demo order has three lines, priced by the unchanged step 1 code: 2 × large latte with oat milk and vanilla syrup (10.80), 1 × small espresso with an extra shot (3.20), and 1 × large tea (3.00). The subtotal is 17.00.
At 16:00, best_for(large, 16:00) finds happy hour, because 16:00 is
not before the start and is before the end.
- Latte line:
percent_off(1080, 20)is (21,600 + 50) / 100 = 216 in integer division, so 2.16 off, and the line costs 8.64. - Espresso line: small, so
best_forreturns a null pointer. No discount; the line costs 3.20. - Tea line:
percent_off(300, 20)is (6,000 + 50) / 100 = 60, so 0.60 off, and the line costs 2.40.
The discount is 2.16 + 0.60 = 2.76, and the total is 17.00 − 2.76 = 14.24, which is also 8.64 + 3.20 + 2.40. At 15:59 no promotion is running, so the total is 17.00.
Placing an order fixes its price. The queue now holds a reference to
a clock and owns its promotions. place reads the clock once and stores
the time and the Quote with the order, so a promotion that ends while
the drinks are made changes nothing the customer has already paid.
VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
PlaceResult OrderQueue::place(Order order) { if (order.empty()) return Rejection{Problem::empty_order, "add a drink first"}; // One reading of the clock, used for both the time stamp and the price, // so the two always agree. const TimeOfDay now = clock_.now(); Quote price = quote(order, promotions_, now); const OrderNumber number = next_number_++; // use this number, then move the counter on orders_.emplace(number, PlacedOrder{number, std::move(order), Status::placed, now, std::move(price)}); return number;}The step 2 demo previews the order at 15:59 and 16:00, places it at 17:59 and again at 18:00, and looks at both at 18:30:
Preview at 15:59: 2 x large latte + oat milk + vanilla syrup: 10.80 1 x small espresso + extra shot: 3.20 1 x large tea: 3.00 Subtotal 17.00, discount 0.00, total 17.00Preview at 16:00: 2 x large latte + oat milk + vanilla syrup: 10.80 - 2.16 happy hour = 8.64 1 x small espresso + extra shot: 3.20 1 x large tea: 3.00 - 0.60 happy hour = 2.40 Subtotal 17.00, discount 2.76, total 14.24Placed at 17:59 as order 1, pays 14.24Placed at 18:00 as order 2, pays 17.00At 18:30: order 1 (placed 17:59) still pays 14.24, order 2 pays 17.00What changed.
- New:
clock.hpp(TimeOfDay,Clock,ManualClock) andpromotion.hpp/promotion.cpp(percent_off,Promotion,Promotions,Quote,quote). Order::total()becameOrder::subtotal(), because “the total” now depends on the time. Every caller that showed a total had to switch to aQuote.OrderQueuegained a constructor that takesconst Clock&andPromotions, and apreviewfor the screen.PlacedOrdergainedplaced_atandquote.
What did not change. money.hpp, rejection.hpp, menu.hpp, and
menu.cpp are identical in both steps. price_line, Order::add, and
OrderQueue::advance are unchanged. The step 1 tests still pass in
step 2, adapted only for the rename and the queue’s new constructor.
What made the change cheap or expensive.
- Cheap: step 1 priced every line in one function and kept money in cents. The discount is a separate step on top of the menu price, so none of the step 1 checks changed, and the one new rounding rule sits in one function.
- Cheap: lines were values with their prices copied in, so a
Quotecan copy a line and add a discount without touching the order. - Expensive: step 1 treated
total()as “the price”, and an order’s price did not depend on time. That assumption was spread over every caller, so the rename touched them all, and the queue needed a clock it never had.
A judgement to know about. The discount is rounded once per line, not per drink. Three large lattes at 25% on one line are 13.50 × 25% = 3.375, so 3.38 off. Rounded per drink, that would be 1.13 × 3 = 3.39. Per-line rounding also means three separate lines of one latte each get 3.39 off in all. Either rule is defensible; what matters is that the code has one, says which, and tests it (AC-6.5).
Lifetimes in step 2. The queue keeps a reference to the clock, not
a copy, so the clock must outlive the queue. In the tests and the demo
both are local variables and the clock is declared first, so it is
destroyed last. The promotions are taken by value and owned by the
queue; best_for returns a pointer into them, valid as long as the
Promotions object, which never changes after construction.
The new acceptance criteria and their tests.
| AC | Criterion |
|---|---|
| AC-5.1 | Times of day are checked: 00:00 to 23:59 only. |
| AC-5.2 | A promotion set up wrong is refused: no name, a percent outside 1 to 100, a time outside the day, or a window that does not end after it starts. |
| AC-6.1 | Happy hour takes 20% off large lines, options included. |
| AC-6.2 | The window includes its start and excludes its end. |
| AC-6.3 | Other sizes pay the menu price. |
| AC-6.4 | A discount is rounded to the nearest cent, a half up. |
| AC-6.5 | The discount is rounded once per line, not per drink. |
| AC-6.6 | Promotions do not add up; the biggest wins, and a tie goes to the first listed. |
| AC-6.7 | The quote’s totals add up line by line. |
| AC-6.8 | The price is fixed when the order is placed. |
| AC-6.9 | An empty order is still refused. |
Step 2 has 29 tests: the 18 from step 1 and these 11. A mutation check in a scratch copy of step 2 made 12 small deliberate bugs, in the rounding, the window’s ends, the tie rule, the size filter, the promotion checks, the status steps, the drink limit, and the time an order is priced; the tests caught all 12.
VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
LLD_TEST(ac_6_1_happy_hour_takes_20_percent_off_large_lines_options_included) { const Menu menu = test_menu(); const Promotions promotions({happy_hour}); // 2 x (4.50 + 0.50 + 0.40) = 10.80; 20% is 2.16. const QuotedLine line = only_line( menu, {"latte", Size::large, {Option::oat_milk, Option::vanilla_syrup}, 2}, promotions, at(17, 0)); LLD_CHECK_EQ(line.line.line_total, cents(1080)); LLD_CHECK_EQ(line.promotion, std::optional<std::string>{"happy hour"}); LLD_CHECK_EQ(line.discount, cents(216)); LLD_CHECK_EQ(line.total, cents(864));}
LLD_TEST(ac_6_2_the_window_includes_its_start_and_excludes_its_end) { const Menu menu = test_menu(); const Promotions promotions({happy_hour}); const LineRequest large_tea{"tea", Size::large, {}, 1}; const auto discount_at = [&](TimeOfDay time) { return only_line(menu, large_tea, promotions, time).discount; }; LLD_CHECK_EQ(discount_at(at(15, 59)), cents(0)); LLD_CHECK_EQ(discount_at(at(16, 0)), cents(60)); LLD_CHECK_EQ(discount_at(at(17, 59)), cents(60)); LLD_CHECK_EQ(discount_at(at(18, 0)), cents(0)); LLD_CHECK_EQ(only_line(menu, large_tea, promotions, at(18, 0)).promotion, std::optional<std::string>{});}
LLD_TEST(ac_6_3_other_sizes_pay_the_menu_price) { const Menu menu = test_menu(); const Promotions promotions({happy_hour}); for (const Size size : {Size::small, Size::medium}) { const QuotedLine line = only_line(menu, {"latte", size, {}, 3}, promotions, at(17, 0)); LLD_CHECK_EQ(line.discount, cents(0)); LLD_CHECK_EQ(line.total, line.line.line_total); LLD_CHECK_EQ(line.promotion, std::optional<std::string>{}); }}
LLD_TEST(ac_6_4_a_discount_is_rounded_to_the_nearest_cent_half_up) { // The rule on its own: below a half rounds down, a half and above up. LLD_CHECK_EQ(percent_off(cents(455), 15), cents(68)); // 68.25 LLD_CHECK_EQ(percent_off(cents(450), 25), cents(113)); // 112.5 LLD_CHECK_EQ(percent_off(cents(430), 15), cents(65)); // 64.5 LLD_CHECK_EQ(percent_off(cents(449), 1), cents(4)); // 4.49 LLD_CHECK_EQ(percent_off(cents(451), 10), cents(45)); // 45.1 LLD_CHECK_EQ(percent_off(cents(459), 10), cents(46)); // 45.9 LLD_CHECK_EQ(percent_off(cents(1), 49), cents(0)); // 0.49 LLD_CHECK_EQ(percent_off(cents(1), 50), cents(1)); // 0.5 LLD_CHECK_EQ(percent_off(cents(450), 100), cents(450)); // everything LLD_CHECK_EQ(percent_off(cents(0), 20), cents(0));}
LLD_TEST(ac_6_5_the_discount_is_rounded_once_per_line_not_per_drink) { const Menu menu = test_menu(); const Promotions quarter_off({{"quarter off", Size::large, 25, at(16, 0), at(18, 0)}}); // 3 x 4.50 = 13.50; 25% is 3.375, so 3.38 off. Per drink it would be // 1.13 * 3 = 3.39. const QuotedLine line = only_line(menu, {"latte", Size::large, {}, 3}, quarter_off, at(17, 0)); LLD_CHECK_EQ(line.discount, cents(338)); LLD_CHECK_EQ(line.total, cents(1012));}
LLD_TEST(ac_6_6_promotions_do_not_add_up_the_biggest_wins) { const Menu menu = test_menu(); const Promotion ten{"ten off", Size::large, 10, at(15, 0), at(17, 0)}; const Promotion thirty{"thirty off", Size::large, 30, at(16, 30), at(17, 30)}; const Promotions promotions({ten, happy_hour, thirty}); const LineRequest large_tea{"tea", Size::large, {}, 1}; // 3.00 const auto at_time = [&](TimeOfDay time) { return only_line(menu, large_tea, promotions, time); }; LLD_CHECK_EQ(at_time(at(15, 30)).discount, cents(30)); // only ten off LLD_CHECK_EQ(at_time(at(16, 15)).discount, cents(60)); // ten and happy hour: 20% LLD_CHECK_EQ(at_time(at(17, 0)).discount, cents(90)); // happy hour and thirty: 30% LLD_CHECK_EQ(at_time(at(17, 0)).promotion, std::optional<std::string>{"thirty off"}); LLD_CHECK_EQ(at_time(at(17, 45)).discount, cents(60)); // happy hour only // A tie goes to the promotion listed first. const Promotion also_twenty{"also twenty", Size::large, 20, at(16, 0), at(18, 0)}; LLD_CHECK_EQ(only_line(menu, large_tea, Promotions({also_twenty, happy_hour}), at(17, 0)) .promotion, std::optional<std::string>{"also twenty"}); LLD_CHECK_EQ(only_line(menu, large_tea, Promotions({happy_hour, also_twenty}), at(17, 0)) .promotion, std::optional<std::string>{"happy hour"});}
LLD_TEST(ac_6_7_the_quote_totals_add_up_line_by_line) { const Menu menu = test_menu(); Order order; LLD_CHECK( !order.add(menu, {"latte", Size::large, {Option::oat_milk, Option::vanilla_syrup}, 2})); LLD_CHECK(!order.add(menu, {"espresso", Size::small, {Option::extra_shot}, 1})); LLD_CHECK(!order.add(menu, {"tea", Size::large, {}, 1})); const Quote q = quote(order, Promotions({happy_hour}), at(17, 0)); LLD_CHECK_EQ(q.lines.size(), std::size_t{3}); // 10.80 + 3.20 + 3.00 = 17.00; discounts 2.16 + 0.00 + 0.60 = 2.76. LLD_CHECK_EQ(q.subtotal, order.subtotal()); LLD_CHECK_EQ(q.subtotal, cents(1700)); LLD_CHECK_EQ(q.discount, cents(276)); LLD_CHECK_EQ(q.total, cents(1424)); Money sum; for (const QuotedLine& line : q.lines) sum += line.total; LLD_CHECK_EQ(sum, q.total); // No promotions at all: the quote is the step-1 total. const Quote plain = quote(order, Promotions{}, at(17, 0)); LLD_CHECK_EQ(plain.discount, cents(0)); LLD_CHECK_EQ(plain.total, order.subtotal());}
LLD_TEST(ac_6_8_the_price_is_fixed_when_the_order_is_placed) { const Menu menu = test_menu(); ManualClock clock(at(17, 58)); OrderQueue queue(clock, Promotions({happy_hour})); const Order order = order_of(menu, {"tea", Size::large, {}, 2}); // 6.00 // The preview follows the clock; it is not a promise. LLD_CHECK_EQ(queue.preview(order).total, cents(480)); clock.set(at(17, 59)); const OrderNumber early = place(queue, order); clock.set(at(18, 0)); LLD_CHECK_EQ(queue.preview(order).total, cents(600)); const OrderNumber late = place(queue, order); clock.set(at(19, 0)); const PlacedOrder* first = queue.find(early); const PlacedOrder* second = queue.find(late); LLD_CHECK(first != nullptr && second != nullptr); if (first == nullptr || second == nullptr) return; LLD_CHECK_EQ(first->placed_at, at(17, 59)); LLD_CHECK_EQ(first->quote.total, cents(480)); LLD_CHECK_EQ(first->quote.discount, cents(120)); LLD_CHECK_EQ(second->placed_at, at(18, 0)); LLD_CHECK_EQ(second->quote.total, cents(600)); // Moving through the statuses does not reprice it either. LLD_CHECK(!queue.advance(early, Status::preparing)); LLD_CHECK_EQ(queue.find(early)->quote.total, cents(480));}
LLD_TEST(ac_6_9_an_empty_order_is_still_refused) { ManualClock clock(at(17, 0)); OrderQueue queue(clock, Promotions({happy_hour})); const PlaceResult result = queue.place(Order{}); const auto* rejection = std::get_if<Rejection>(&result); LLD_CHECK(rejection != nullptr); if (rejection != nullptr) LLD_CHECK_EQ(rejection->problem, Problem::empty_order); LLD_CHECK(queue.numbers_in(Status::placed).empty()); // The refusal used no number: the first real order is still order 1. LLD_CHECK_EQ(place(queue, one_tea(test_menu())), 1);}Common mistakes
Section titled “Common mistakes”Rounding twice
Section titled “Rounding twice”Flawed (intentional)Demonstrates a mistake on purpose. Do not copy it; see the corrected version.
// Flawed: each line shows its own rounded discount on the receipt, but the// order's discount is worked out again from the lines added up.Money order_discount(const Order& order, const Promotion& promotion) { Money discounted; for (const OrderLine& line : order.lines()) { if (line.request.size == promotion.size) discounted += line.line_total; } return percent_off(discounted, promotion.percent); // a second rounding}It goes wrong on the return line, which rounds a second time. Take a
25% promotion on large drinks and an order of a large latte (4.50) and a
large tea with oat milk (3.50). The receipt lines show 1.13 and 0.88 off,
which is 2.01, but this function returns 25% of 8.00, which is 2.00. The
receipt then says 6.00 at the bottom while its lines add up to 5.99.
IllustrativeA fragment for explanation; not compiled on its own.
// The order's discount is the line discounts added up: one rounding each.Money order_discount(const Quote& quote) { Money sum; for (const QuotedLine& line : quote.lines) sum += line.discount; return sum;}This is what quote does, which is why its total is the subtotal minus
the summed discounts (AC-6.7).
Lines that point at the menu
Section titled “Lines that point at the menu”Flawed (intentional)Demonstrates a mistake on purpose. Do not copy it; see the corrected version.
// Flawed: a line that points at the menu item and looks the price up later.struct PointingLine { const MenuItem* item = nullptr; // points into a Menu's vector of items Size size = Size::medium; int quantity = 1;};
Money line_total(const PointingLine& line) { // Reads the menu now, not when the line was added. return line.item->prices.at(line.size) * line.quantity;}It goes wrong in line_total, at line.item->. The pointer is valid
only while the menu that owns the item exists. In test AC-3.2 the menu
is destroyed before the total is read, and with this line type that read
is undefined behaviour. And if the menu could ever be edited in place, a
price change would silently reprice every open order, which stage 2
ruled out (an assumption the owner accepted).
IllustrativeA fragment for explanation; not compiled on its own.
// The line copies what it needs when it is added, as OrderLine does.struct CopiedLine { std::string name; // copied from the menu item Size size = Size::medium; int quantity = 1; Money unit_price; // copied: later menu changes do not reach it};
Money line_total(const CopiedLine& line) { return line.unit_price * line.quantity; }Reading the time inside the pricing code
Section titled “Reading the time inside the pricing code”Flawed (intentional)Demonstrates a mistake on purpose. Do not copy it; see the corrected version.
// Flawed: the price asks the operating system for the time itself.Quote price_now(const Order& order, const Promotions& promotions) { const std::time_t seconds = std::time(nullptr); std::tm local{}; localtime_r(&seconds, &local); // POSIX: the kiosk's local time return quote(order, promotions, at(local.tm_hour, local.tm_min));}It goes wrong at std::time(nullptr). The function works, but no test
can say “it is 18:00”, so AC-6.2 and AC-6.8 can only be checked by
running the tests at the right minute. The call to localtime_r also
ties the pricing code to one operating system’s API.
IllustrativeA fragment for explanation; not compiled on its own.
// The caller says where "now" comes from: a ManualClock in tests.Quote price_now(const Order& order, const Promotions& promotions, const Clock& clock) { return quote(order, promotions, clock.now());}All six sketches in this section compile (syntax only) against the step 2 headers with g++ and clang++. They are not part of the example, and only the first was run, to produce the numbers above.
Limitations
Section titled “Limitations”This is a teaching example, not a kiosk you could install.
- In memory only. A restart loses every open order, and numbers start at 1 again. The owner accepted that; a real shop might not.
- No payment, no receipts, no tax. The example stops at the price.
- No concurrency. One kiosk and one bar screen on one thread. A
second kiosk would need the queue to be shared safely, which is a
redesign, not a lock added later:
findhands out pointers into the queue, and a lock inside the queue cannot protect a read made through them after the call returns. - The queue only grows. Collected orders are never removed, which is fine for one shift in memory but not for a long-running system.
- No screen. The demo stands in for the kiosk and bar screens.
- A fixed menu. Sizes and options are enums, so a new option is a rebuild. Loading the menu from a file would need a parser and its own error reporting.
- No real clock. Step 2 has only
ManualClock. A real kiosk would add a clock that reads the local time, which nothing in the example could test.
Exercise
Section titled “Exercise”Exercise: Cancel an order before the bar starts it
The owner changes their mind about stage 2: “Customers should be able to cancel from the kiosk, as long as the bar has not started the drinks. The till refunds what they paid.”
Starting from step 2:
- Decide how a cancelled order is represented. Is it removed from the queue, or does it stay with a new status?
- Write the declaration and definition of
OrderQueue::cancel. What does it return, and which refusals does it give? - Say what
advanceandnumbers_indo with a cancelled order. - List the tests you would add, with their acceptance criteria.
Show the explained answer
Keep the order, with a new status. Removing it would lose the record
the till needs for the refund, and it would turn every pointer from
find for that number into a dangling one. So add cancelled to
Status (and to its to_string), and make next_after(cancelled)
return an empty optional, as for collected. Because next_after
never returns cancelled, advance can never move an order there:
cancelling is its own operation with its own rule.
Return the refund, or why not. The amount to refund is the price
fixed when the order was placed, which step 2 already stores in
PlacedOrder::quote.
IllustrativeA fragment for explanation; not compiled on its own.
// In OrderQueue (order_queue.hpp):// Cancels an order the bar has not started. Refuses an unknown number// (unknown_order) and an order that is not placed (step_not_allowed).// Returns the amount to give back: the price fixed when it was placed.std::variant<Money, Rejection> cancel(OrderNumber number);
// In order_queue.cpp:std::variant<Money, Rejection> OrderQueue::cancel(OrderNumber number) { const auto found = orders_.find(number); if (found == orders_.end()) { return Rejection{Problem::unknown_order, "no order " + std::to_string(number)}; } PlacedOrder& placed = found->second; if (placed.status != Status::placed) { return Rejection{Problem::step_not_allowed, "order " + std::to_string(number) + " is " + std::string(to_string(placed.status)) + ", cannot be cancelled"}; } placed.status = Status::cancelled; return placed.quote.total;}This answer was compiled and checked in a scratch copy of step 2, not in the example itself.
The rest follows. advance refuses every move of a cancelled
order with step_not_allowed, through the same comparison that
already refuses moves of a collected order. numbers_in(Status::cancelled)
lists cancelled orders, oldest first, with no change.
Tests to add.
- AC-4.8: a placed order can be cancelled; its status becomes cancelled, and the refund is its placed price. For example, two large teas placed at 17:59 under happy hour and cancelled at 18:30 refund 4.80, not 6.00.
- AC-4.9: an order that is preparing, ready, collected, or already cancelled cannot be cancelled, and its status does not change.
- AC-4.10: cancelling an unknown number is refused with
unknown_order. - AC-4.11:
advancerefuses every move of a cancelled order.
What to notice. The change was cheap because the status rule lives in one function and the price was already fixed at placement. A design that recomputed the price on demand would have to decide which price to refund.
Summary
Section titled “Summary”- Listen for nouns, verbs, and rules, then ask the questions that change the design, and mark which answers are your assumptions.
- Write requirements as behaviour, with acceptance criteria that become test names.
- Work out what each choice forces and rules out before writing code.
- Compare at least two honest designs. Here, options differ only in price and permission, which is data, so a menu held as data beats a class per option. With options that behave differently, it might not.
- Keep ownership plain: values and copies, borrowed references only for a call, and pointers that the owner guarantees.
- When time matters, inject a clock, round in one place, and fix the price when the order is placed.