From domain concepts to code
What you will learn on this page
Section titled “What you will learn on this page”- Why “one class per noun” gives a model that looks thorough and works badly.
- How to test each candidate class against the behaviour it must support.
- Four ways to shrink a model: merge, drop, demote to a value, and demote to a field.
- When a plain function, a value, or a count is enough, and a class is not.
The problem statement
Section titled “The problem statement”A small theatre sells tickets for its events. Each event has a title, a start time, and a fixed number of seats. Seating is general admission: there are no seat numbers. A customer buys one or more tickets for an event, if enough seats remain, until the event starts. The price per ticket is set per event. A customer can return a ticket, for a full refund, up to 24 hours before the event starts. The box office can show a sales summary for each event.
This lesson builds the model twice. The first iteration follows the nouns. The second follows the behaviour. Both compile, and comparing them is the lesson.
First iteration: a class for every noun
Section titled “First iteration: a class for every noun”Underline the nouns: theatre, ticket, event, title, start time, seat, customer, price, refund, box office, sales summary. Make each one a class, connect them where the statement mentions them together, and the result is:
VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// FLAWED on purpose: one class for every noun in the problem statement.// These three lines are forward declarations: they tell the compiler "a// class with this name exists, defined later", so the classes below can// hold pointers to it before its full definition appears.class Customer;class Event;class Seat;
// A class wrapping one number with no rules of its own.
class Price {public: std::int64_t cents = 0;};
// A ticket points at its event, its seat, and its buyer. A raw pointer// (`T*`) here means "knows about, does not own": the ticket never deletes// what it points at, and nothing guarantees the object is still alive.// `= nullptr` starts each pointer as "points at nothing".class Ticket {public: Event* event = nullptr; Seat* seat = nullptr; Customer* customer = nullptr;};
// One object per seat, although the seats are all the same: the only useful// fact is how many are taken. `ticket` points back at the Ticket that points// at this seat, so every sale and refund must update both sides.class Seat {public: bool taken = false; Ticket* ticket = nullptr;};
class Customer {public: std::string name; // A second back link: pointers to this customer's tickets. std::vector<Ticket*> tickets; // must agree with each Ticket::customer};
class Event {public: std::string title; int starts_at_hour = 0; Price price; std::vector<Seat> seats; // 300 seats that are all the same};
// Refund and SalesSummary are results of an operation, not things the// theatre keeps; here they are classes because the words appeared.class Refund {public: Ticket* ticket = nullptr; Price amount;};
class SalesSummary {public: Event* event = nullptr; int sold = 0; Price revenue;};
class Theatre {public: // A std::vector keeps its elements side by side. When it runs out of // room, push_back moves every element to a new block of memory, so a // Ticket::event pointer into it would point at freed memory (dangle). std::vector<Event> events; // adding one may move all the others};
// Where every rule ends up, reaching through pointers into every other// class. Its three operations are only declared, never defined: their// bodies are never written.class BoxOffice {public: // Stores the theatre's address (`&theatre`); the box office does not own // it, so the theatre must outlive the box office. explicit BoxOffice(Theatre& theatre) : theatre_(&theatre) {} bool sell(Event& event, Customer& customer, int quantity, int now_hour); Refund refund(Ticket& ticket, int now_hour); SalesSummary summarise(Event& event);
private: Theatre* theatre_; // The same vector problem: the next sale may reallocate this, and every // Seat::ticket and Customer::tickets pointer then dangles. std::vector<Ticket> tickets_; // Seat::ticket and Customer::tickets point in here};Text description of the diagram
Nine boxes and fourteen arrows. Solid “owns” arrows, each with a count: Theatre owns the events;
BoxOffice owns the tickets; each Event owns its seats and a Price; Refund and
SalesSummary each own a Price. Dashed “knows” arrows, each a raw pointer in the code:
BoxOffice points to the theatre; each Ticket points to its event, its seat, and its customer;
Refund points to a ticket; SalesSummary points to an event. Two dashed arrows point back: from
Seat to Ticket (knows 0..1) and from Customer to Ticket (knows 0..*), so two pairs are
linked in both directions.
Diagram source (Mermaid)
flowchart LR
Theatre -->|"owns 0..*"| Event
BoxOffice -.->|knows 1| Theatre
BoxOffice -->|"owns 0..*"| Ticket
Event -->|"owns 1..*"| Seat
Event -->|owns 1| Price
Ticket -.->|knows 1| Event
Ticket -.->|knows 1| Seat
Ticket -.->|knows 1| Customer
Seat -.->|knows 0..1, back| Ticket
Customer -.->|"knows 0..*, back"| Ticket
Refund -.->|knows 1| Ticket
Refund -->|owns 1| Price
SalesSummary -.->|knows 1| Event
SalesSummary -->|owns 1| PriceIt looks complete: every concept in the statement has a home. Now test it against the behaviour.
- Seats. Seating is general admission. For an event with 300 seats, 300
Seatobjects that are all the same carry one useful fact: how many are taken. The model has turned a count into a collection that must be searched and kept in step with the tickets. - Two-way links. A ticket points to its customer, and the customer holds a list of pointers back to its tickets. A seat points to its ticket and the ticket to its seat. Every sale and every refund must update both sides of each link, or the model contradicts itself.
- Pointers into vectors.
Seat::ticketandCustomer::ticketspoint intoBoxOffice::tickets_, astd::vector. The next sale may reallocate it, and every one of those pointers then dangles.Theatre::eventshas the same problem forTicket::event. - Classes with no behaviour.
Pricewraps one number.RefundandSalesSummaryare results of an operation, not things the theatre keeps.Theatreholds the events and does nothing else. - Customer. No behaviour in the statement needs a customer’s name, or anything about a customer except “who bought this”. The class exists because the word did.
- The rules have no home. Where does “until the event starts” live? “24
hours before”? “If enough seats remain”? Not on
Seat,Ticket, orCustomer. They all end up inBoxOffice, which has to reach through pointers into every other class to apply them.
The nouns were a useful list of candidates. The mistake was to treat the list as the design.
Start from behaviour instead
Section titled “Start from behaviour instead”The statement describes three operations. For each, list what must be known and decided, as in the responsibilities lesson:
- Sell n tickets for an event, at time t. Does the event exist? Has it started? Do n seats remain? Then: count the seats as sold, and issue n ticket numbers, recording each one’s event and buyer.
- Take back a ticket, at time t. Was this ticket issued, and not already returned? Is t at least 24 hours before the event? Then: give one seat back, forget the ticket, and refund the event’s price.
- Summarise an event. Seats sold, seats remaining, revenue.
Now ask of each candidate: which of these questions does it answer, or which of these actions does it carry out? A candidate that answers none is not a class in this model.
Merge, drop, demote
Section titled “Merge, drop, demote”Four moves shrink the candidate list to a model:
| Candidate | Move | Becomes | Why |
|---|---|---|---|
Seat |
Demote to a field | int sold_ in Event |
Seats are interchangeable. A count answers “do n remain?”. |
Price |
Demote to a field | std::int64_t price_cents_ in Event |
One number with no rules of its own here. (With currencies, Money would return.) |
Customer |
Demote to a value | CustomerId |
Only “who bought it” is needed: an identity, with no behaviour. |
Ticket |
Demote to a value | TicketNumber, plus a private record of event and buyer |
The customer holds a number; the box office holds the facts. |
Refund |
Demote to a value | the Return result, with the amount |
It is the answer to “take back”, not something kept. |
SalesSummary |
Demote to a value | a SalesSummary struct, computed when asked |
A report, derived from the event’s data. |
Theatre |
Drop | nothing | It would only hold the events, which the box office already must. |
BoxOffice |
Merge with Theatre | BoxOffice, owning events and ticket records |
It is where the three operations happen, and where cross-object rules have one owner. |
Event |
Keep | Event |
It knows its start time, capacity, price, and seats sold, and guards the seat count. |
Two classes with behaviour remain. Everything else became a value, a field, or nothing.
Second iteration: the classes the behaviour needs
Section titled “Second iteration: the classes the behaviour needs”VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// Times are whole hours since the box office opened: enough for "24 hours// before". A real system would use std::chrono.// `using Hour = int;` is only a second name for int (an alias). It makes// signatures readable, but the compiler still accepts any int as an Hour.using Hour = int;
// Three ID types, each a struct wrapping an int. Because they are different// types, passing a TicketNumber where an EventId is expected will not// compile. The defaulted operator<=> (the "spaceship" operator) asks the// compiler to write ==, <, >, and the rest by comparing `value`; std::map// needs `<` to keep its keys sorted. `friend` lets it be declared inside the// struct while still being a free function.struct EventId { int value; friend auto operator<=>(const EventId&, const EventId&) = default;};
struct TicketNumber { int value; friend auto operator<=>(const TicketNumber&, const TicketNumber&) = default;};
struct CustomerId { int value; friend auto operator<=>(const CustomerId&, const CustomerId&) = default;};
// What the box office reports for one event: a value, computed when asked.// Money is a whole number of cents, so there is no rounding. std::int64_t is// a 64-bit integer, large enough for any realistic revenue.struct SalesSummary { int sold = 0; int remaining = 0; std::int64_t revenue_cents = 0;};The three IDs are small structs with defaulted comparisons. They are separate
types, so a ticket number cannot be passed where an event ID is expected.
SalesSummary is a plain struct of results. Hour is only an alias for
int, so, unlike the IDs, it will not stop a wrong number being passed. Time is
a plain hour count, which is enough for “24 hours before”; a
real system would use std::chrono.
VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// An event with general admission: seats are interchangeable, so a count// is enough. Invariant: 0 <= sold() <= capacity().class Event {public: // Throws std::invalid_argument if capacity < 1 or the price is negative, // so every Event starts valid, with no seats sold. A price of 0 (a free // event) is allowed. Event(std::string title, Hour starts_at, int capacity, std::int64_t price_cents);
[[nodiscard]] const std::string& title() const noexcept { return title_; } [[nodiscard]] Hour starts_at() const noexcept { return starts_at_; } [[nodiscard]] std::int64_t price_cents() const noexcept { return price_cents_; } [[nodiscard]] int capacity() const noexcept { return capacity_; } [[nodiscard]] int sold() const noexcept { return sold_; } [[nodiscard]] int remaining() const noexcept { return capacity_ - sold_; }
// Marks `count` seats as sold, all or nothing. // Returns false, changing nothing, if count < 1 or fewer than `count` // seats remain. [[nodiscard]]: a caller that ignores a false would sell // tickets for seats it did not get. [[nodiscard]] bool reserve(int count) noexcept; // Gives one sold seat back. Does nothing if no seats are sold. void release_one() noexcept;
// These two are the only functions that change sold_, and both keep it // between 0 and capacity_: that is how the invariant is kept.
private: std::string title_; Hour starts_at_; int capacity_; std::int64_t price_cents_; int sold_ = 0;};VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// All or nothing: either every seat asked for is taken, or none is.bool Event::reserve(int count) noexcept { // Check first, change second. A count below 1 is refused too, so a // negative count cannot be used to "unsell" seats. if (count < 1 || count > remaining()) { return false; } sold_ += count; // safe: count <= remaining(), so sold_ stays <= capacity_ return true;}
// The guard keeps sold_ from going below 0 if nothing is sold.void Event::release_one() noexcept { if (sold_ > 0) --sold_;}Event is an entity with one invariant: sold seats are between zero and the
capacity. reserve either takes all the seats asked for or none, which is the
“if enough seats remain” rule, kept by the object that knows the count. It also
refuses a count below 1, and release_one does nothing when no seat is sold,
so no call can move the count out of range.
VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// The result of sell: what happened, plus the ticket numbers the buyer needs// next. The enum is nested, so it is written Sale::Result::sold.struct Sale { enum class Result { sold, no_such_event, too_late, not_enough_seats }; Result result; std::vector<TicketNumber> tickets; // empty unless sold};
// The result of take_back: what happened, plus the refund amount.struct Return { enum class Result { refunded, no_such_ticket, too_late }; Result result; std::int64_t refund_cents = 0; // zero unless refunded};
// The coordinator. It owns every Event and every ticket record, and applies// the rules that need an event, a ticket, and the current time together.class BoxOffice {public: // The return deadline as a named constant: one value for the whole class // (`static`), fixed when the program is compiled (`constexpr`). static constexpr Hour hours_before_start_to_return = 24;
// Takes the event by value and keeps it, under `id`. // Throws std::invalid_argument if the ID is already used. void add_event(EventId id, Event event);
// Sells `quantity` tickets in one go, or none. Sales close when the // event starts. Throws std::invalid_argument if quantity < 1. [[nodiscard]] Sale sell(EventId event, CustomerId customer, int quantity, Hour now); // Full refund up to 24 hours before the event starts: at hour // starts_at - 24 itself it is still allowed, one hour later it is not. // A returned ticket is forgotten, so returning it again reports // no_such_ticket. [[nodiscard]] Return take_back(TicketNumber ticket, Hour now); // The event's totals, or std::nullopt (an empty optional) if there is no // event with that ID. [[nodiscard]] std::optional<SalesSummary> summary(EventId event) const;
private: struct IssuedTicket { // the record of a sale; no behaviour of its own EventId event; CustomerId customer; };
// Everything owned by value and found by ID: nothing holds a pointer // that could dangle when a map changes. std::map<EventId, Event> events_; std::map<TicketNumber, IssuedTicket> tickets_; // only tickets not yet returned int next_ticket_ = 1; // the number the next ticket sold will get};VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// Sells `quantity` tickets for one event at hour `now`, all or none.// A quantity below 1 is a caller's bug, so it throws; every other refusal is// an ordinary answer, returned in the Sale.Sale BoxOffice::sell(EventId event_id, CustomerId customer, int quantity, Hour now) { if (quantity < 1) { throw std::invalid_argument("BoxOffice::sell: quantity must be at least 1"); } // find returns an iterator to the (ID, Event) entry, or end() if there // is none. const auto found = events_.find(event_id); if (found == events_.end()) { // Builds a Sale from the braces: the result, then `{}`, an empty // list of tickets. return {Sale::Result::no_such_event, {}}; } // found->second is the Event inside the map. `Event&` is a reference to // it, not a copy, so reserve() below changes the stored event. Event& event = found->second; // Sales close when the event starts: at the start hour itself, too late. if (now >= event.starts_at()) { return {Sale::Result::too_late, {}}; } // The event keeps its own seat count. If reserve refuses, nothing has // changed anywhere. if (!event.reserve(quantity)) { return {Sale::Result::not_enough_seats, {}}; } // The seats are now sold: issue one ticket record per seat. Sale sale{Sale::Result::sold, {}}; for (int i = 0; i < quantity; ++i) { // next_ticket_++ hands out the current number, then adds one, so // ticket numbers are 1, 2, 3, ... and never reused. const TicketNumber number{next_ticket_++}; // Record which event and which customer this ticket is for. tickets_.emplace(number, IssuedTicket{event_id, customer}); sale.tickets.push_back(number); } return sale;}
// Takes a ticket back at hour `now` and refunds the event's full price, if// the ticket exists and it is at least 24 hours before the start.
Return BoxOffice::take_back(TicketNumber ticket, Hour now) { const auto found = tickets_.find(ticket); // Never issued, or already returned (a returned ticket is erased below). if (found == tickets_.end()) { // refund_cents is left out of the braces, so it takes its default, 0. return {Return::Result::no_such_ticket}; } // The ticket record holds its event's ID; at() looks the event up. at() // would throw std::out_of_range for a missing key, but every ticket was // issued for an event in the map, and events are never removed. Event& event = events_.at(found->second.event); // The deadline is starts_at - 24. `>` (not `>=`) means the deadline hour // itself still counts: for a start at hour 100, hour 76 is allowed and // hour 77 is too late. if (now > event.starts_at() - hours_before_start_to_return) { return {Return::Result::too_late}; } event.release_one(); // Forget the ticket, so it cannot be returned twice. `found` is invalid // after this line and is not used again. tickets_.erase(found); return {Return::Result::refunded, event.price_cents()};}
// A query (`const`): the event's totals, or std::nullopt if no event has// this ID.std::optional<SalesSummary> BoxOffice::summary(EventId event_id) const { const auto found = events_.find(event_id); if (found == events_.end()) { return std::nullopt; } const Event& event = found->second; // Built on demand from the event's count, so it can never be out of date. // sold() is an int and price_cents() a std::int64_t, so the product is // worked out in 64 bits. A SalesSummary converts to the optional. return SalesSummary{event.sold(), event.remaining(), event.sold() * event.price_cents()};}How this code works: BoxOffice::sell and BoxOffice::take_back
Both functions check first and change second, so every refusal leaves the box office exactly as it was.
sell, in order:
- A quantity below 1 throws
std::invalid_argument: asking for zero tickets is a bug in the caller, not a customer’s request. - Look up the event. If there is none, return
no_such_event. - If
nowis at or after the start hour, returntoo_late. - Ask the event to
reservethe seats.reserveis all or nothing, so afalsemeans no seat was taken, andsellreturnsnot_enough_seats. - Only now, with the seats counted as sold, issue one ticket number per
seat.
next_ticket_++gives out the current number and then adds one, so numbers are never reused, even after a return. Each number is recorded intickets_with its event and buyer, and added to theSale.
take_back, in order:
- Look up the ticket number. A number that was never issued, or was already
returned, is not in
tickets_: returnno_such_ticket. - Find the ticket’s event by the
EventIdin its record. - If
nowis afterstarts_at() - 24, returntoo_late. The deadline hour itself is still allowed. - Give one seat back, erase the record (so the same ticket cannot be returned twice), and refund the event’s price.
A trace of the program below. The event starts at hour 100, has 3 seats, and costs 2 500 cents. The return deadline is hour 76.
| Step | What decides it | Result | sold after |
Tickets on record |
|---|---|---|---|---|
| customer 7 buys 2 at hour 10 | 10 is before 100; all 3 seats remain | sold, tickets 1, 2 |
2 | 1, 2 |
| customer 8 buys 2 at hour 11 | only 1 seat remains | not_enough_seats |
2 | 1, 2 |
| ticket 1 returned at hour 50 | 50 is not after 76 | refunded, 2 500 |
1 | 2 |
| ticket 2 returned at hour 90 | 90 is after 76 | too_late |
1 | 2 |
| customer 8 buys 2 at hour 91 | 91 is before 100; 2 seats remain | sold, tickets 3, 4 |
3 | 2, 3, 4 |
summary(play) then reports 3 sold, 0 remaining, and 3 × 2 500 = 7 500
cents of revenue. The revenue is worked out from the current count, so the
refunded ticket is not in it.
BoxOffice is the coordinator. It owns the events and the ticket records by
value, in maps keyed by ID, so nothing holds a pointer that could dangle: a
ticket refers to its event by EventId, and the customer holds only a
TicketNumber. The time rules (sales close at the start; returns close 24 hours
before) live here, because they involve a ticket record, an event, and the
current time together.
Sale and Return are results: they report what happened and carry what the
caller needs next, the ticket numbers or the refund amount. That replaces the
first iteration’s Refund class.
VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
BoxOffice office;const EventId play{1};// Three seats at 2'500 cents ($25.00) each. The ' in 2'500 is only a// digit separator for readability. The Event is moved into the office.// text(), defined above main, turns a result into the words printed.//// The story, in order (the deadline for returns is 100 - 24 = 76):// 1. Customer 7 buys two of the three seats at hour 10: tickets 1 and 2.// 2. Customer 8 asks for two when only one is left, and gets none.// 3. Ticket 1 (first.tickets.at(0); at() checks the index and would throw// if the sale had issued no tickets) is returned at hour 50, before// the deadline. Ticket 2 is brought back at hour 90, after it.// 4. The returned seat makes two free, so customer 8's second try works.// 5. `*office.summary(play)` takes the SalesSummary out of the optional// and copies it into `totals`. Safe because the event certainly// exists; `*` on an empty optional would be undefined behaviour.office.add_event(play, Event{"The Tempest", 100, 3, 2'500}); // starts at hour 100
const Sale first = office.sell(play, CustomerId{7}, 2, 10);std::cout << "customer 7 buys 2: " << text(first.result) << '\n';std::cout << "customer 8 buys 2: " << text(office.sell(play, CustomerId{8}, 2, 11).result) << '\n';
const Return early = office.take_back(first.tickets.at(0), 50);std::cout << "return at hour 50: " << text(early.result) << ", " << early.refund_cents << " cents\n";std::cout << "return at hour 90: " << text(office.take_back(first.tickets.at(1), 90).result) << '\n';std::cout << "customer 8 buys 2: " << text(office.sell(play, CustomerId{8}, 2, 91).result) << '\n';
const SalesSummary totals = *office.summary(play);std::cout << "sold " << totals.sold << ", remaining " << totals.remaining << ", revenue " << totals.revenue_cents << " cents\n";customer 7 buys 2: soldcustomer 8 buys 2: refused: not enough seatsreturn at hour 50: refunded, 2500 centsreturn at hour 90: refused: less than 24 hours to gocustomer 8 buys 2: soldsold 3, remaining 0, revenue 7500 centsThe event starts at hour 100 and has three seats. The first return, at hour 50,
is more than 24 hours before the start, so it is refunded and the seat comes
back. Customer 8’s first request for two seats failed because only one was
left, and reserve is all or nothing. The second return, at hour 90, is too
late. That leaves one seat from the first
sale, plus the two customer 8 then buys: three sold, $25.00 each.
Text description of the diagram
Six boxes. Solid arrows go from BoxOffice to Event, labelled “owns 0..*, by EventId”, and to
IssuedTicket, a private record, labelled “owns 0..*, by TicketNumber”. A dashed arrow goes from
IssuedTicket to Event, labelled “knows 1, by EventId”: the record holds the event’s ID, not a
pointer. Dashed arrows labelled “creates and returns” go from BoxOffice to the result values
Sale, Return, and SalesSummary. There are no other arrows, no pointers, and no connection
runs in both directions.
Diagram source (Mermaid)
flowchart LR
BoxOffice -->|"owns 0..*, by EventId"| Event
BoxOffice -->|"owns 0..*, by TicketNumber"| IssuedTicket["IssuedTicket (private record)"]
IssuedTicket -.->|"knows 1, by EventId"| Event
BoxOffice -.->|creates and returns| Sale
BoxOffice -.->|creates and returns| Return
BoxOffice -.->|creates and returns| SalesSummaryclass BoxOffice
the coordinator: owns events and sale records; applies the time rules
Data members
std::map<EventId, Event> events_;std::map<TicketNumber, IssuedTicket> tickets_;IssuedTicket: a private struct of EventId and CustomerIdint next_ticket_ = 1;static constexpr Hour hours_before_start_to_return = 24;
Member functions
void add_event(EventId id, Event event);Sale sell(EventId event, CustomerId customer, int quantity, Hour now);Return take_back(TicketNumber ticket, Hour now);std::optional<SalesSummary> summary(EventId event) const;
class Event
entity: sold* stays between 0 and capacity*
Data members
std::string title_;Hour starts_at_;int capacity_;std::int64*t price_cents*;int sold_ = 0;
Member functions
Event(std::string title, Hour starts_at, int capacity, std::int64_t price_cents);int remaining() const;bool reserve(int count);all or nothingvoid release_one();
struct Sale
result value
Data members
Result result;sold, no_such_event, too_late, not_enough_seatsstd::vector<TicketNumber> tickets;empty unless sold
struct Return
result value
Data members
Result result;refunded, no_such_ticket, too_latestd::int64_t refund_cents = 0;
Compare the outline’s data members with the first iteration’s code. Every
connection that was a pointer is now either a value inside a map
(std::map<EventId, Event>) or an ID (EventId event inside the record).
That is why the only “knows” arrow left is labelled “by EventId”: it is an ID,
not a pointer, and nothing points back.
Testing the second iteration
Section titled “Testing the second iteration”VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// LLD_TEST(name) defines one test. LLD_CHECK(condition) records a failure if// the condition is false; LLD_CHECK_EQ(actual, expected) does the same for// `actual == expected` and prints both values when they differ;// LLD_CHECK_THROWS(expression, type) fails unless the expression throws// that type. They come from the site's small test header, lld_test.hpp.//// What the first three tests prove:// - a_sale_is_all_or_nothing: asking for 4 of 3 seats sells none (sold stays// 0); asking for exactly 3 sells all three and issues three ticket// numbers. size() returns a std::size_t, so the expected count is written// as std::size_t{3}, keeping both sides of == the same type.// - sales_close_when_the_event_starts: hour 99 is the last hour to buy; at// hour 100 the show has started.// - returns_are_allowed_up_to_24_hours_before: the deadline is 100 - 24 =// 76. A return at 76 gets the full price back; at 77 it is refused, so// only one of the two seats is given back.//// namespace { ... } with no name keeps these helpers private to this file.namespace {
// The one event every test uses. constexpr: a constant fixed at compile time.constexpr EventId show{1};
// Copies the summary out of the optional, so that checks do not refer into a// temporary that has already been destroyed. value() takes the summary out// of the optional, and throws std::bad_optional_access if it is empty.SalesSummary summary_of(const BoxOffice& office) { return office.summary(show).value(); }
// A box office with one event, `show`: starts at hour 100, `capacity` seats,// 1'000 cents each. Returned by value; the office is moved out, not shared.BoxOffice office_with_show(int capacity) { BoxOffice office; office.add_event(show, Event{"Show", 100, capacity, 1'000}); return office;}
} // namespace
LLD_TEST(a_sale_is_all_or_nothing) { BoxOffice office = office_with_show(3); LLD_CHECK(office.sell(show, CustomerId{1}, 4, 0).result == Sale::Result::not_enough_seats); LLD_CHECK_EQ(summary_of(office).sold, 0); const Sale sale = office.sell(show, CustomerId{1}, 3, 0); LLD_CHECK(sale.result == Sale::Result::sold); LLD_CHECK_EQ(sale.tickets.size(), std::size_t{3}); LLD_CHECK_EQ(summary_of(office).remaining, 0);}
LLD_TEST(sales_close_when_the_event_starts) { BoxOffice office = office_with_show(3); LLD_CHECK(office.sell(show, CustomerId{1}, 1, 99).result == Sale::Result::sold); LLD_CHECK(office.sell(show, CustomerId{1}, 1, 100).result == Sale::Result::too_late);}
LLD_TEST(returns_are_allowed_up_to_24_hours_before) { BoxOffice office = office_with_show(3); const Sale sale = office.sell(show, CustomerId{1}, 2, 0); const Return last_chance = office.take_back(sale.tickets.at(0), 76); // exactly 24 hours LLD_CHECK(last_chance.result == Return::Result::refunded); LLD_CHECK_EQ(last_chance.refund_cents, std::int64_t{1'000}); LLD_CHECK(office.take_back(sale.tickets.at(1), 77).result == Return::Result::too_late); LLD_CHECK_EQ(summary_of(office).sold, 1);}
// The record is erased on the first return, so the second finds nothing and// the seat count is not given back twice.LLD_TEST(a_returned_ticket_cannot_be_returned_again) { BoxOffice office = office_with_show(3); const Sale sale = office.sell(show, CustomerId{1}, 1, 0); LLD_CHECK(office.take_back(sale.tickets.at(0), 0).result == Return::Result::refunded); LLD_CHECK(office.take_back(sale.tickets.at(0), 0).result == Return::Result::no_such_ticket); LLD_CHECK_EQ(summary_of(office).sold, 0);}
// The refusals the statement leaves implicit: an unknown event is an answer// (no_such_event, and an empty summary); a quantity of 0 and a repeated// event ID are caller bugs, so they throw.LLD_TEST(unknown_events_and_bad_quantities) { BoxOffice office = office_with_show(3); LLD_CHECK(office.sell(EventId{9}, CustomerId{1}, 1, 0).result == Sale::Result::no_such_event); LLD_CHECK(!office.summary(EventId{9})); // an empty optional converts to false // sell is [[nodiscard]]; static_cast<void> says "result ignored on purpose". LLD_CHECK_THROWS(static_cast<void>(office.sell(show, CustomerId{1}, 0, 0)), std::invalid_argument); LLD_CHECK_THROWS(office.add_event(show, Event{"Again", 1, 1, 0}), std::invalid_argument);}
// Event alone, with no BoxOffice: no call can push the count below 0 or// above the capacity of 2.LLD_TEST(an_event_keeps_its_seat_count_in_range) { Event event{"Show", 100, 2, 1'000}; LLD_CHECK(!event.reserve(0)); LLD_CHECK(!event.reserve(-1)); event.release_one(); // nothing sold yet: no change LLD_CHECK_EQ(event.sold(), 0); LLD_CHECK(event.reserve(2)); LLD_CHECK(!event.reserve(1)); LLD_CHECK_EQ(event.remaining(), 0);}Four tests are one sentence each of the problem statement: a sale is all or
nothing; sales close at the start; returns are allowed up to exactly 24 hours
before; a ticket cannot be returned twice. A fifth checks the refusals the
statement leaves implicit (an unknown event, a quantity below 1, a repeated
event ID), and a sixth checks that Event keeps its seat count in range. Most
test through BoxOffice, the class whose behaviour the statement describes. The first iteration would be hard to test
this way: there is no operation to call until someone writes BoxOffice::sell,
and then it would need seats, customers, and pointers set up by hand.
summary_of copies the summary out of its std::optional before checking it.
An early version of these tests wrote office.summary(show)->sold inside a
check, which refers into a temporary std::optional that is destroyed before
the check reads it. AddressSanitizer reported it as a stack-use-after-scope in
the site’s sanitizer build; the other builds passed silently.
When a class is needed
Section titled “When a class is needed”The second iteration is not “fewer classes is better”. Each move above was justified by the behaviour, and a change in behaviour reverses it:
- Numbered seats (“customer chooses seat F12”) would bring
Seatback, or at least a seat number per ticket, because seats would no longer be interchangeable. - Customer accounts (“customers see their past tickets and get e-mails”)
would make
Customeran entity with data and behaviour of its own. - Several currencies would turn
price_cents_back into aMoneyvalue. - Several venues with different rules would give
Theatre(asVenue) a responsibility at last.
A good test for each candidate: what would break, or become harder, if this were a value, a field, or nothing? If the answer is “nothing”, it is not yet a class.
Common mistakes
Section titled “Common mistakes”- Taking the noun list as the design. Nouns are candidates, not classes.
- Modelling the real world instead of the problem. Real theatres have seats; this problem only needs to count them.
- Two-way links by default. Each needs keeping in step. Add the second direction only when an operation needs it, and prefer IDs to pointers for long-lived links.
- Classes for the results of operations, such as
Refund. A result is usually a returned value. - Stopping at the first iteration. A first model is a draft. Testing it against each operation, before writing much code, is cheap.
When a requirement changes
Section titled “When a requirement changes”New requirement: “Members of the theatre’s club get 10% off, and can buy tickets a week before everyone else.”
Now a customer has a fact the behaviour needs, club membership, so CustomerId
alone is no longer enough. The box office needs to ask “is this customer a club
member?” That does not necessarily make Customer a full entity inside the box
office. A MembershipDirectory that answers that one question by ID may be
enough. Each event gains a second date, when public sales open, and sell gains
one more check. The price rule could be a small function of the event’s price
and the customer’s membership. Each change lands in a few predictable
places, because each rule has one owner.
Exercise: Prune a noun list into a model
A gym lets members book places in fitness classes. Each class has a name, an instructor’s name, a room, a start time, and a maximum number of places. A member may book one place per class, and may hold at most 5 bookings at a time. A member can cancel a booking until 2 hours before the class. When a class is full, members can join a waiting list; when a place is cancelled, the first member waiting gets it automatically.
Candidate nouns: gym, member, fitness class, name, instructor, room, start time, place, booking, waiting list.
- For each candidate, choose: keep as a class, merge, drop, demote to a value, or demote to a field. Justify each choice from the behaviour.
- Which rules need a coordinator, and which belong to one class?
Show the explained answer
-
One reasonable model:
- Fitness class: keep as an entity,
FitnessClass. It knows its capacity, its bookings, and its waiting list, and guards “no more bookings than places”. - Place: demote to a field. Places are interchangeable, like the theatre’s seats: the class’s capacity and its number of bookings are enough.
- Booking: demote to a value inside the fitness class: the set of
MemberIds booked. “One place per class” is then “noMemberIdtwice in that set”, a rule the fitness class can guard. - Waiting list: demote to a field of the fitness class, a
std::deque<MemberId>(first in, first out). It has a rule (promote the first member on a cancellation), but that rule involves the class’s bookings too, so it lives with them. - Member: demote to a value,
MemberId, unless more behaviour appears. But note the 5-booking limit (see question 2). - Name, instructor, room, start time: fields of the fitness class. Nothing in the behaviour needs the instructor or room to have behaviour. (A rule like “an instructor cannot teach two classes at once” would change that.)
- Gym: drop, or merge into a
BookingDeskcoordinator that owns the fitness classes.
- Fitness class: keep as an entity,
-
One class: capacity, one place per member per class, the waiting list, and promotion on cancellation all involve only one
FitnessClass, so it can keep them. Coordinator: “at most 5 bookings at a time” involves every class a member has booked, so no singleFitnessClasscan check it. ABookingDeskthat owns the classes can count a member’s bookings (or keep a count per member) before asking a class to book. The 2-hour cancellation rule involves the current time and the class’s start time; it could be onFitnessClass(given the time) or on the desk. Either is reasonable; the page’s box office put its time rules on the coordinator.Watch one interaction: promoting a waiting member when a place is cancelled must also respect that member’s 5-booking limit. That makes promotion a coordinator decision, not only the fitness class’s.
Summary
Section titled “Summary”- Nouns in a problem statement are candidates, not classes.
- List the operations the problem needs, and test each candidate against them: which question does it answer, which action does it carry out?
- Shrink the model by merging, dropping, demoting to a value, or demoting to a field. Keep a class when it has its own data and its own rule.
- Prefer ownership by value and IDs over webs of pointers, and avoid two-way links until an operation needs them.
- Every pruning decision depends on the behaviour; when the behaviour changes, revisit it.