Skip to content

Case study: library management

Difficulty: Intermediate

Key concepts

  • titles versus copies
  • entities and value objects
  • std::variant status
  • aggregates
  • repositories
  • passing dates in
  • outcomes as values
  • requirement changes
  • Why “book” is two things, a title and a copy, and how mixing them up makes the commonest questions impossible to answer.
  • How a copy’s status can be one value (on the shelf, on loan to one member, or set aside for one member) so that a copy can never be in two places at once.
  • Where the rules live when the data lives in a database: a service that reads and saves through repositories, and why each repository returns a copy of what it stores.
  • Why a library’s refusals (“that copy is out”, “you owe fines”) are values, and which mistakes are still exceptions.
  • How to treat dates as an input, so that “21 days late” can be tested without waiting 21 days.
  • How a change of rule (one waiting member per title becomes a queue) stays inside one type, and how the compiler lists the places that must change.

This page follows the order in How to approach a case study. It assumes Repository and Unit of Work and Multiplicity and lifecycle.

“Design a library management system.”

“Library management” can mean a catalogue search, an acquisitions system, inter-library loans, e-books, or the desk where books go in and out. The first job is to find out which one, and what it must get right.

Each question is here because its answer changes the design.

Question Answer (from the client) What it changes
Which part of the library? Lending at one branch: the desk and the self-service kiosk. Search and buying books are other systems. Loans, returns, holds, and fines. No catalogue search.
When a member asks for a book, do they want that book? Any copy of the title will do. Some popular titles have ten copies. Title (what is published) and copy (what is on the shelf) are separate.
How long is a loan? Renewals? 21 days. Renew up to twice, 21 days from the day of renewal. Not if it is overdue, and not if someone is waiting for the title. Loan period, renewal count, two refusals.
How many books can a member have? Five at a time. A limit checked across all of a member’s loans.
Fines? 0.25 a day late, at most 10.00 for one loan. Owing 5.00 or more stops borrowing until they pay some. Fine rule, a cap, a block, and payments.
Can members reserve a book that is out? Yes, a hold on the title. Today, one member per title: the paper hold card. When a copy comes back it is kept for them for 3 days. Holds on titles; a hold shelf; expiry. (The change later replaces the one card.)
Do you keep a record of who borrowed what? No. Once a book is back, we do not keep who had it. Privacy policy. No loan history: a loan exists only while the copy is out.
Where are the records kept? The city’s database. Your team will not have it for a few months; build against something we can swap. Rules kept apart from storage: repositories (NFR-1).
How big? About 40,000 copies, 8,000 members, a few hundred loans a day, two desks and a kiosk. Single process for now; concurrency matters once the database is shared.

The answer about history deserves a second look. Without it, a design would likely have a Loan table that grows forever. With it, a loan is just “this copy is out with this member until this date”, which is part of the copy’s status. One answer removed a class.

Confirmed: titles, copies, and members; check out, renew, check in; fines and payments; one hold per title; the hold shelf and its expiry.

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

  • Staff add titles, copies, and members; there is no removal yet.
  • Due dates do not skip the days the branch is closed.
  • Every member has the same limits. No child or staff categories.
  • A copy set aside counts as “not on the shelf” for holds.
  • The morning job that clears the hold shelf runs once a day, before opening.

Out of scope: search, buying books, other branches, lost and damaged copies, notifications (email or text), e-books, and reports.

Functional

  • FR-1 Staff list a title (ISBN, name, author), add copies of it with a barcode each, and add members.
  • FR-2 A member checks out a copy on the shelf for 21 days. A member has at most five copies at once, and cannot borrow while owing 5.00 or more.
  • FR-3 A member renews a loan for 21 days from the day of renewal, at most twice. Not if the loan is overdue, nor if someone waits for the title, nor while the member owes 5.00 or more.
  • FR-4 Checking a copy in ends the loan. A late copy costs 0.25 per day after the due date, at most 10.00 per loan, added to what the member owes.
  • FR-5 A member places a hold on a title when no copy is on the shelf. At most one member waits for a title.
  • FR-6 A copy that comes free (returned, newly added, or not collected in time) goes to the member waiting, if any. It is set aside for them for 3 days, and only they can borrow it.
  • FR-7 A member cancels their hold, including one whose copy is already set aside.
  • FR-8 A member pays some or all of what they owe.
  • FR-9 A member’s current loans and due dates can be listed.

Non-functional

  • NFR-1 The rules do not depend on where records are kept. They are tested without a database, and the city’s database can be added without changing them.
  • NFR-2 Dates are calendar days, passed in by the caller. The rules never read a clock.
  • NFR-3 Money is a whole number of cents in a 64-bit integer.
  • NFR-4 Each action answers at the desk at once. (Not measured; the in-memory store scans its copies, which a database would replace with an index.)

The tests are named after these criteria. See Use cases, user stories, and acceptance criteria.

UC-1 Check out.

  • AC-1.1 A copy on the shelf is lent for 21 days; the due date is 21 days after today.
  • AC-1.2 A copy that is out is refused, even to the member who has it.
  • AC-1.3 The sixth loan is refused.
  • AC-1.4 Owing 5.00 or more is refused; once the member pays below 5.00, borrowing works again.
  • AC-1.5 A copy set aside is lent only to the member it is set aside for.
  • AC-1.6 An unknown member or copy is refused.

UC-2 Renew.

  • AC-2.1 A renewal sets the due date 21 days from today; the third renewal is refused.
  • AC-2.2 A renewal is refused if the copy is not on loan to this member, if it is overdue, if someone waits for the title, or while the member owes 5.00 or more; the due date is unchanged.

UC-3 Check in.

  • AC-3.1 On or before the due date: no fine, and the copy is on the shelf.
  • AC-3.2 After it: 0.25 per day late, at most 10.00 for the loan.
  • AC-3.3 If a member waits for the title, the copy is set aside for them until the end of the third day, and their hold is met.
  • AC-3.4 A copy that was not out is refused.

UC-4 Holds.

  • AC-4.1 A hold is placed only when no copy of the title is on the shelf.
  • AC-4.2 A member who has a copy, or already waits, cannot hold the title; a second member cannot hold it while one waits.
  • AC-4.3 A copy not collected by the end of its last day goes, the next morning, to a member who has placed a hold since, or back to the shelf.
  • AC-4.4 Cancelling ends the hold; if a copy was set aside, it goes on as in AC-4.3.
  • AC-4.5 A new copy of a title someone waits for is set aside for them.

UC-5 Fines.

  • AC-5.1 Paying reduces what is owed; paying nothing, or more than is owed, is refused.

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

  • INV-1 A copy is in exactly one place: on the shelf, on loan to one member, or set aside for one member. (The CopyStatus type)
  • INV-2 No member has more than five copies on loan. (Library::check_out)
  • INV-3 If a member waits for a title, no copy of it is on the open shelf. (place_hold refuses then; every function that frees a copy calls route)
  • INV-4 A copy set aside is lent only to its member. (check_out, and Copy::lend as a second guard)
  • INV-5 What a member owes is never negative, and one loan adds at most 10.00. (Member::pay, check_in)

INV-3 is the interesting one. It is not about one object: it links a title’s hold to the status of every copy of that title. No single class can keep it alone, so the design must make sure every path that puts a copy on the shelf asks first whether someone is waiting. That is why route exists, and why the tests check INV-3 after every simulated day.

The nouns from the answers: library, branch, book, title, copy, ISBN, barcode, member, loan, due date, renewal, fine, payment, hold, hold shelf, desk, kiosk, database. Filtered:

  • Title is the book as published, identified by its ISBN. It is an entity: the same title stays the same as its holds change. Becomes Title.
  • Copy is one physical book with a barcode. Also an entity, with its own identity: two copies of the same title are different copies. Becomes Copy.
  • Member has an ID, a name, and what they owe. Becomes Member.
  • ISBN, barcode, and member ID are identifiers. Each becomes its own small type, so a barcode cannot be passed where an ISBN is wanted. See Strong types.
  • Loan exists only while a copy is out, and records who has it, the due date, and the renewals. With no history to keep, it is part of the copy’s status, not an entity of its own.
  • Hold is “this member waits for this title”. It belongs to the title. Once a copy is set aside, the copy’s status records who it is for.
  • Hold shelf is a place a copy can be, not a thing with behaviour. It is one of the copy’s statuses.
  • Fine is an amount added to what the member owes; payment an amount taken off. Neither needs a class.
  • Library, desk, kiosk: the desk and kiosk call the library; the library is the service that applies the rules.
  • Database: outside. The rules see it through repositories.
Entity sketch of the library (step 1). Solid arrows: has, refers to, or is one of. Dashed arrows: uses without owning
Text description of the diagram

A Title is identified by an Isbn and a Copy by a Barcode. Each Copy is a copy of one Title, which it refers to by ISBN. Each Copy has exactly one CopyStatus, which is one of OnShelf, OnLoan, or OnHoldShelf. OnLoan and OnHoldShelf each refer to one Member by ID. A Title may refer to at most one waiting Member by ID. The Library uses the repositories without owning them, and the repositories store titles, copies, and members. Nothing holds a pointer to another object; every link is an identifier.

Diagram source (Mermaid)
flowchart LR
Title -->|"identified by"| Isbn
Copy -->|"identified by"| Barcode
Copy -->|"is a copy of, by ISBN"| Title
Copy -->|has exactly one| Status[CopyStatus]
Status -->|is one of| OnShelf
Status -->|is one of| OnLoan
Status -->|is one of| OnHoldShelf
OnLoan -->|"refers to, by id"| Member
OnHoldShelf -->|"refers to, by id"| Member
Title -->|"0..1 waiting member, by id"| Member
Library -.->|uses| Repos[Repositories]
Repos -.->|store| Title
Repos -.->|store| Copy
Repos -.->|store| Member

Every link between the three entities is an identifier, not a pointer or a reference. That matters for storage: a database row has no pointer to give, and a copy loaded today must not point into a member loaded yesterday. It also sets the aggregate boundaries: a title with its hold, a copy with its status, and a member with their fines are each loaded and saved whole.

The design below is step 1 of the example, the complete answer to FR-1 … FR-9. The hold queue is added in When the requirements change.

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

types.hpp
// A calendar day. Loans and fines count whole days, never hours.
// `using` gives an existing type a shorter name: Date *is*
// std::chrono::sys_days, a count of days since 1 January 1970. Adding
// days{21} to a Date gives the date three weeks later, and subtracting
// two Dates gives the number of days between them.
using Date = std::chrono::sys_days;
// Money in whole cents, never floating point: 0.25 is stored as 25, so
// adding fines is exact. std::int64_t is a 64-bit signed integer, far
// larger than any fine.
using Cents = std::int64_t;
// A member's number, wrapped in its own type. A plain int would let a
// caller pass any number, such as a count of loans, where a member was
// meant; a separate type makes that a compile error. Written MemberId{1}.
struct MemberId {
std::uint32_t value = 0;
// `<=>` (the "spaceship" operator) set to `= default` asks the
// compiler to write ==, !=, <, <=, >, and >= by comparing `value`.
// == is needed to compare two ids, < to use MemberId as a std::map key.
auto operator<=>(const MemberId&) const = default;
};
// The book as published: one ISBN, however many copies the library owns.
// A value object: it checks its text once, when it is made, so every Isbn
// that exists is well formed, and two Isbns with the same digits are equal.
class Isbn {
public:
// Thirteen digits. The check digit is not verified, a known limitation.
// `explicit` stops a plain std::string turning into an Isbn without the
// caller writing Isbn(...). The parameter is taken by value and moved
// into digits_ (std::move hands over the text instead of copying it),
// so the checks below look at digits_, not at the moved-from parameter.
// find_first_not_of returns the position of the first character that is
// not a digit, or std::string::npos ("no position") if every one is.
// Throws std::invalid_argument for anything else, so no bad Isbn exists.
explicit Isbn(std::string digits) : digits_(std::move(digits)) {
if (digits_.size() != 13 ||
digits_.find_first_not_of("0123456789") != std::string::npos) {
throw std::invalid_argument("an ISBN has 13 digits: " + digits_);
}
}
const std::string& str() const { return digits_; }
// Compares by the digits: needed to find a title by ISBN in a std::map.
auto operator<=>(const Isbn&) const = default;
private:
std::string digits_;
};
// One physical copy: the label stuck inside the cover.
// The same pattern as Isbn: checked once, compared by its text.
class Barcode {
public:
// Any label that is not empty. Throws std::invalid_argument for "".
explicit Barcode(std::string label) : label_(std::move(label)) {
if (label_.empty()) throw std::invalid_argument("a barcode cannot be empty");
}
const std::string& str() const { return label_; }
auto operator<=>(const Barcode&) const = default;
private:
std::string label_;
};

Isbn and Barcode are value objects: they check their text once, in the constructor, and compare by value. Date is std::chrono::sys_days, a count of days with calendar arithmetic: due + days{21} and today - due are exact, and no time of day can creep in.

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

title.hpp
// A plain struct: four public members and no rules of its own to guard.
// Title{isbn, name, author, hold} lists them in this order. A title is
// stored and loaded as a whole, hold included, by TitleRepository.
struct Title {
Isbn isbn;
std::string name;
std::string author;
// Step 1: at most one member waits for a title. The optional says so
// in the type; there is no second place to put another member.
// Empty (std::nullopt) means nobody is waiting; holding a MemberId
// means that member is waiting for the next free copy.
std::optional<MemberId> hold;
};

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

copy.hpp
// The three places a copy can be. Each is its own small struct holding
// only the data that makes sense in that place.
// On the open shelf: anyone may borrow it, and there is nothing to record.
struct OnShelf {};
// Out with a member: who has it, when it is due back, and how many times
// the loan has been renewed (it starts at 0).
struct OnLoan {
MemberId member;
Date due;
int renewals = 0;
};
// Set aside for a member who placed a hold. `until` is the last day
// they can collect it.
struct OnHoldShelf {
MemberId member;
Date until;
};
// A std::variant holds exactly one of the listed types at a time, like a
// box with one compartment that can take any one of three shapes. So a
// copy is on the shelf, or on loan, or on the hold shelf, never two at
// once, and the borrower and due date exist only while it is on loan.
// std::holds_alternative<OnLoan>(status) asks which one it holds, and
// std::get_if<OnLoan>(&status) gives a pointer to it, or nullptr if the
// variant holds something else.
using CopyStatus = std::variant<OnShelf, OnLoan, OnHoldShelf>;

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

copy.hpp
// Each change of status checks the copy's own state, and throws
// std::logic_error if it is called from the wrong one: that is a bug in
// the caller. The Library checks first, and reports the expected
// refusals ("that copy is out") as values.
// A Copy is an entity: it is known by its barcode, and its status changes
// over time. It names its title by ISBN (a value), not by a pointer, so a
// Copy can be copied, stored, and loaded on its own.
class Copy {
public:
Copy(Barcode barcode, Isbn isbn); // a new copy starts on the shelf
const Barcode& barcode() const { return barcode_; }
const Isbn& isbn() const { return isbn_; }
// Read-only access to the status: callers can look, but can change it
// only through the five functions below, which enforce the rules.
const CopyStatus& status() const { return status_; }
// From OnShelf, or from OnHoldShelf for this member. Becomes OnLoan to
// `member`, due on `due`, with no renewals yet.
void lend(MemberId member, Date due);
// From OnLoan; counts the renewal. Sets the new due date and adds 1 to
// renewals; the borrower stays the same.
void renew(Date new_due);
// From OnLoan to OnShelf. Returns the loan that ended, for the fine.
OnLoan take_back();
// From OnShelf. Becomes OnHoldShelf for `member`, to collect by `until`.
void set_aside(MemberId member, Date until);
// From OnHoldShelf to OnShelf.
void reshelve();
private:
Barcode barcode_;
Isbn isbn_;
// Starts as OnShelf{}: a new copy is on the open shelf.
CopyStatus status_ = OnShelf{};
};

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

member.hpp
// A library member and what they owe. A class, not a plain struct,
// because the balance has a rule: it can only go up by a real fine and
// down by a payment that does not take it below zero. The only way to
// change fines_ is through charge and pay, so the rule cannot be skipped.
class Member {
public:
// The name is taken by value and moved in (std::move hands over the
// text without copying it). A new member owes nothing.
Member(MemberId id, std::string name) : id_(id), name_(std::move(name)) {}
MemberId id() const { return id_; }
const std::string& name() const { return name_; }
Cents fines() const { return fines_; }
// Adds a fine. A zero or negative "fine" is a bug in the caller, so it
// throws std::invalid_argument rather than being quietly accepted.
void charge(Cents fine) {
if (fine <= 0) throw std::invalid_argument("a fine is positive");
fines_ += fine;
}
// INV-5: what a member owes is never negative.
// Accepts 1 cent up to the whole balance; anything else throws
// std::invalid_argument and leaves fines_ unchanged. Library::pay checks
// the same range first and returns Outcome::bad_amount instead.
void pay(Cents amount) {
if (amount <= 0 || amount > fines_) {
throw std::invalid_argument("pay between 0.01 and what is owed");
}
fines_ -= amount;
}
private:
MemberId id_;
std::string name_;
Cents fines_ = 0;
};

Title is a plain struct: its only rule, “at most one waiting member”, is said by its type, std::optional<MemberId>. Copy and Member are classes because they have rules about how their data may change: a copy moves between statuses only in the allowed ways, and what a member owes never goes below zero.

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

repositories.hpp
// One repository per aggregate. Each find returns a copy of what is
// stored: the caller changes it and gives it back with save.
// Each class is an interface: `virtual ... = 0` declares a function with
// no body here ("pure virtual"), which every concrete repository must
// write. Library holds a TitleRepository& and so works with any of them.
// The virtual destructor makes it safe to destroy a concrete repository
// through a pointer to the interface.
class TitleRepository {
public:
virtual ~TitleRepository() = default;
// The title with this ISBN, or std::nullopt if there is none. The
// result is a copy: changing it changes nothing stored until save.
virtual std::optional<Title> find(const Isbn& isbn) const = 0;
// Stores the title under its ISBN, adding it or replacing the old one.
virtual void save(const Title& title) = 0;
};
// The same find and save, by barcode, plus three searches. Each search
// returns a std::vector of copies (possibly empty), not references into
// the store, so the caller may save while looping over the result.
class CopyRepository {
public:
virtual ~CopyRepository() = default;
virtual std::optional<Copy> find(const Barcode& barcode) const = 0;
virtual void save(const Copy& copy) = 0;
// The questions the rules ask, in the library's words.
// Every copy of a title; the copies on loan to one member; and every
// copy waiting on the hold shelf.
virtual std::vector<Copy> copies_of(const Isbn& isbn) const = 0;
virtual std::vector<Copy> on_loan_to(MemberId member) const = 0;
virtual std::vector<Copy> on_hold_shelf() const = 0;
};
class MemberRepository {
public:
virtual ~MemberRepository() = default;
virtual std::optional<Member> find(MemberId id) const = 0;
virtual void save(const Member& member) = 0;
};

The interfaces speak the library’s language: “the copies of this title”, “the copies on loan to this member”. They say nothing about tables or files. Each find returns a copy of what is stored, in a std::optional; the caller changes it and gives it back with save. That is the choice Repository and Unit of Work explains: a database has no object to hand out a reference to, and a copy has no lifetime rule to break.

For the tests and the demo, the repositories are maps in memory:

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

memory_store.hpp
// Titles in a std::map, sorted by ISBN (which is why Isbn needs the `<`
// that its defaulted <=> provides). `final` means no class can derive from
// this one; `override` asks the compiler to check that each function
// really replaces one declared in TitleRepository.
class InMemoryTitles final : public TitleRepository {
public:
// map::find returns an iterator: a position in the map, or end() if
// the key is not there. it->second is the stored Title; returning it
// copies it into the std::optional, so the caller gets its own copy.
std::optional<Title> find(const Isbn& isbn) const override {
const auto it = titles_.find(isbn);
if (it == titles_.end()) return std::nullopt;
return it->second;
}
// insert_or_assign adds the key if it is new and replaces the stored
// value if it is not: "save" means both "add" and "update" here.
void save(const Title& title) override { titles_.insert_or_assign(title.isbn, title); }
private:
std::map<Isbn, Title> titles_;
};
// Copies in a std::map keyed by barcode, so the scans below visit them in
// barcode order (M1 before S1 before S2).
class InMemoryCopies final : public CopyRepository {
public:
std::optional<Copy> find(const Barcode& barcode) const override {
const auto it = copies_.find(barcode);
if (it == copies_.end()) return std::nullopt;
return it->second;
}
void save(const Copy& copy) override { copies_.insert_or_assign(copy.barcode(), copy); }
// Each search hands `matching` a small test to apply to every copy.
// The test is a lambda; [&] lets it read `isbn` (or `member`) from the
// enclosing function by reference, which is safe because matching
// finishes before the function returns.
std::vector<Copy> copies_of(const Isbn& isbn) const override {
return matching([&](const Copy& c) { return c.isbn() == isbn; });
}
// get_if gives a pointer to the OnLoan inside the status, or nullptr if
// the copy is not on loan; only an OnLoan to this member matches.
std::vector<Copy> on_loan_to(MemberId member) const override {
return matching([&](const Copy& c) {
const auto* loan = std::get_if<OnLoan>(&c.status());
return loan != nullptr && loan->member == member;
});
}
// [] captures nothing: this test needs only the copy it is given.
std::vector<Copy> on_hold_shelf() const override {
return matching([](const Copy& c) { return std::holds_alternative<OnHoldShelf>(c.status()); });
}
private:
// A scan of every copy: fine for the tests and the demo. A database
// answers the same question with an index.
// A template: Pred is whatever type of lambda the caller passes, and
// pred(copy) calls it. `const auto& [barcode, copy]` unpacks each map
// entry (a key and value pair) into two names without copying; only a
// copy that matches is copied into the result.
template <typename Pred>
std::vector<Copy> matching(Pred pred) const {
std::vector<Copy> found;
for (const auto& [barcode, copy] : copies_) {
if (pred(copy)) found.push_back(copy);
}
return found;
}
std::map<Barcode, Copy> copies_;
};
// Members in a std::map keyed by MemberId; the same find and save.
class InMemoryMembers final : public MemberRepository {
public:
std::optional<Member> find(MemberId id) const override {
const auto it = members_.find(id);
if (it == members_.end()) return std::nullopt;
return it->second;
}
void save(const Member& member) override { members_.insert_or_assign(member.id(), member); }
private:
std::map<MemberId, Member> members_;
};

class Library

the rules; owns no records

Data members

  • TitleRepository& titles_; not owned; must outlive the library
  • CopyRepository& copies_; not owned
  • MemberRepository& members_; not owned
  • Policy policy_; owned; the numbers from the client

Member functions

  • Outcome check_out(MemberId member, const Barcode& barcode, Date today);
  • Outcome renew(MemberId member, const Barcode& barcode, Date today);
  • CheckIn check_in(const Barcode& barcode, Date today);
  • Outcome place_hold(MemberId member, const Isbn& isbn);
  • Outcome cancel_hold(MemberId member, const Isbn& isbn, Date today);
  • std::vector<Barcode> expire_holds(Date today);
  • Outcome pay(MemberId member, Cents amount);
  • std::vector<Copy> loans_of(MemberId member) const;
  • std::optional<MemberId> route(Copy& copy, Title& title, Date today) const; private: every freed copy goes through it

class Copy

entity; identified by its barcode

Data members

  • Barcode barcode_;
  • Isbn isbn_; which title, by identifier
  • CopyStatus status_; OnShelf, OnLoan, or OnHoldShelf

Member functions

  • const CopyStatus& status() const;
  • void lend(MemberId member, Date due);
  • void renew(Date new_due);
  • OnLoan take_back();
  • void set_aside(MemberId member, Date until);
  • void reshelve();

class Member

entity; identified by its id

Data members

  • MemberId id_;
  • std::string name_;
  • Cents fines_; never negative

Member functions

  • Cents fines() const;
  • void charge(Cents fine);
  • void pay(Cents amount);
The library service and its collaborators in step 1, with the owner of each member

The numbers the client gave are in one place:

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

library.hpp
// The client's numbers, kept together as data instead of being scattered
// through the rules. Each field has a default (`= 21` and so on), so
// Policy{} is the branch's policy; a caller can change one number, such as
// `Policy p; p.max_loans = 1;`. Money is in cents: 25 is 0.25, 1000 is 10.00.
struct Policy {
int loan_days = 21; // a loan, or a renewal, runs this many days
int max_loans = 5; // copies one member may have out at once
int max_renewals = 2; // renewals allowed per loan
int hold_days = 3; // days to collect a copy set aside
Cents fine_per_day = 25; // for each day after the due date
Cents fine_cap = 1000; // most one late loan can cost
Cents blocking_fines = 500; // owing this much stops borrowing
};

And every answer a desk can get is a value:

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

library.hpp
// Everything a desk can be told. Refusals are normal events at a
// library, so they are values; exceptions are kept for bugs and for
// staff setup mistakes.
// Each function that a desk calls returns one of these (check_in returns
// one inside its CheckIn result), and `ok` is the only one that means
// something changed. Every other value is a refusal that changed
// nothing, named so the desk can tell the member why. Where a value
// belongs to one function, its comment starts with that function's job.
enum class Outcome {
ok,
unknown_member,
unknown_copy,
unknown_title,
fines_owed, // the member owes at least the blocking amount
loan_limit, // the member already has the most loans allowed
on_loan, // check out: the copy is out with someone
held_for_another, // check out: the copy is set aside for another member
not_your_loan, // renew: the copy is not on loan to this member
overdue, // renew: bring it back first
renewal_limit, // renew: renewed the most times allowed
holds_waiting, // renew: someone is waiting for the title
not_on_loan, // check in: the copy was not out
copy_on_shelf, // hold: a copy is on the shelf, borrow that
has_a_copy, // hold: the member has a copy, on loan or set aside
already_held, // hold: this member already waits for the title
hold_taken, // hold: another member already waits for the title
no_hold, // cancel: this member has no hold on the title
bad_amount, // pay: not between 0.01 and what is owed
};
Rule Where Why there
A copy is in one place (INV-1) CopyStatus, a std::variant The type cannot say “on loan and on the hold shelf”.
A copy changes status only in allowed ways Copy’s functions The copy’s own data; a wrong call is a bug, so it throws.
Five loans at most (FR-2, INV-2) Library::check_out Needs every copy on loan to the member: a question for the repository, not for one object.
Owing 5.00 blocks borrowing (FR-2) check_out, renew, using Policy A rule about using the member’s balance, not about the balance itself.
Fines are 0.25 a day, at most 10.00 (FR-4) Library::check_in Needs the loan’s due date (from the copy) and changes the member: two aggregates.
What is owed is never negative (INV-5) Member::pay The member’s own data, so the member guards it.
A freed copy goes to the waiting member (FR-6, INV-3) Library::route, called by every path that frees a copy One function, so the rule is written once.
At most one waiting member (FR-5) Title::hold, a std::optional The type has room for one.

check_out checks the copy’s status and returns held_for_another before it calls Copy::lend, and Copy::lend checks again and throws. That is not an accident. The Library reports what a member at the desk needs to hear. The Copy makes sure that no caller, including one written next year, can put it in a state its rules forbid. The first check makes the second one never fire in normal use; the test a_copy_refuses_a_change_from_the_wrong_status makes sure it would.

Trace one path through the outline before writing it: Ana has M1, the only copy of A Field Guide to Moss, due 23 March. Ben holds the title. M1 comes back on 26 March.

  1. check_in(M1, 26 March): copies_.find(M1) gives a copy whose status is OnLoan{ana, 23 March, 0}.
  2. titles_.find gives the title with hold = ben; members_.find(ana) gives Ana.
  3. copy.take_back() returns the ended loan; the status is OnShelf.
  4. Three days late: fine min(3 × 25, 1000) = 75; ana.charge(75).
  5. route(copy, title, 26 March): the title has a hold, so the hold is cleared and the copy is set aside for Ben until 29 March.
  6. The copy, the title, and Ana are saved. The result says: ok, fine 0.75, set aside for Ben.

Each step uses only the outline’s members (including the private route) and the three repositories, so the outline covers this use case. The demo runs exactly this.

The difference from the vending machine is where the behaviour is. There, each customer action meant something different in every state, so each action was a std::visit. Here, most actions accept one status and refuse the rest, so std::get_if and std::holds_alternative read better. The cost is that adding a status will not stop the build at every place that should care. If a fourth status arrived (lost, say), the places to review are the five Copy functions and the status checks in Library, found by searching for the type names.

check_in changes three aggregates: the copy, the title (its hold), and the member (the fine). It works out every change on local copies first and saves them at the end:

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

library.cpp
// A copy comes back to the desk. Ends the loan, charges the borrower for
// each day late (capped), and passes the copy to the member waiting for
// its title, if any. The result (a CheckIn) carries the outcome, the fine
// in cents, and who the copy was set aside for. Changes three records:
// the copy, the title (its hold), and the member (the fine).
CheckIn Library::check_in(const Barcode& barcode, Date today) {
std::optional<Copy> copy = copies_.find(barcode);
// The braces build the CheckIn result from its members in order:
// outcome, fine, set_aside_for. A refusal charges nothing and sets
// nothing aside.
if (!copy) return {Outcome::unknown_copy, 0, std::nullopt};
if (!std::holds_alternative<OnLoan>(copy->status())) {
return {Outcome::not_on_loan, 0, std::nullopt};
}
std::optional<Title> title = titles_.find(copy->isbn());
std::optional<Member> member; // starts empty; filled just below
// An inner block, so `loan` exists only between these braces. loan is
// a reference into the copy's status, and take_back below replaces
// that OnLoan; ending its scope here means it cannot be used after.
// std::get<OnLoan> would throw if the status were not OnLoan, but the
// check above has ruled that out.
{
const auto& loan = std::get<OnLoan>(copy->status());
member = members_.find(loan.member);
}
// A copy whose title or borrower is missing means the stored data is
// broken, which is a bug, not something to tell the desk: it throws.
if (!title || !member) throw std::logic_error("copy refers to a missing title or member");
// Work out every change on local copies first ...
const OnLoan ended = copy->take_back();
// Subtracting two Dates gives a number of days; .count() turns it into
// a plain integer. Zero (back on the due date) or less is not late.
const std::int64_t days_late = (today - ended.due).count();
Cents fine = 0;
if (days_late > 0) {
// 25 cents a day, but never more than fine_cap: 3 days late is
// min(75, 1000) = 75, and 63 days late is min(1575, 1000) = 1000.
// Both arguments are 64-bit integers, as std::min requires.
fine = std::min(days_late * policy_.fine_per_day, policy_.fine_cap);
member->charge(fine);
}
// The copy is now OnShelf; route may set it aside for the waiting
// member and clear the title's hold. Both changes are to local copies.
const std::optional<MemberId> next = route(*copy, *title, today);
// ... then save them. In memory no save can fail; with a database
// these three saves belong in one transaction.
copies_.save(*copy);
titles_.save(*title);
members_.save(*member);
return {Outcome::ok, fine, next};
}
How this code works: Library::check_in

check_in has three parts: load and check, work out the changes, and save.

  1. Load the copy, and refuse early. If the barcode is unknown, or the copy is not on loan, the function returns at once with a CheckIn that has no fine and nobody set aside. Nothing has been changed yet.
  2. Load the other two records. The title comes from the copy’s ISBN. The borrower’s id is inside the copy’s OnLoan, so the code takes a reference to that OnLoan and reads loan.member. The reference is declared inside its own pair of braces, so it ceases to exist at the closing brace. That matters because step 4 replaces the OnLoan: after that, the reference would point at something destroyed.
  3. Check the data is whole. A copy whose title or borrower is missing means the stored data is broken. That is a bug, not a desk refusal, so it throws std::logic_error, still before anything has changed.
  4. Work out the changes, on local copies only. take_back ends the loan and hands back the old OnLoan. today - ended.due is the number of days late. If it is more than zero, the fine is that many days at 25 cents, but no more than 1000, and the member is charged. Then route decides where the copy goes: to the waiting member, or it stays on the open shelf.
  5. Save all three, then return the outcome, the fine, and who the copy was set aside for.

With the values from the trace above. M1 was due on 23 March and comes back on 26 March, with Ben waiting.

Step Value
ended OnLoan{ana, 23 March, 0}; the copy is now OnShelf
days_late 26 − 23 = 3
fine min(3 × 25, 1000) = 75; Ana now owes 75
route the title’s hold was Ben: it is cleared, and M1 is set aside for Ben until 29 March
result {Outcome::ok, 75, ben}

Nothing in steps 1 to 4 can stop halfway through the stores: the only throw comes before any change, charge is only called with a fine above zero, and route is only given a copy on the open shelf. The saves come last, which is why the text below is about what happens if one of them fails.

In memory, a save can fail only if memory runs out, so in practice the three saves all happen. With a database, a failure between them could leave a fine without the return, or a return without the fine. The answer is one transaction per use case, opened by the caller around check_in. This step has no Unit of Work because there is nothing yet for one to coordinate; it is the first thing to add with the database adapter. See Transaction and persistence boundaries.

  • No Loan or Hold repository. A loan is part of a copy, and a hold part of a title. See the trade-off above.
  • No Book base class with Title and Copy deriving from it. They share nothing but the word “book”.
  • No Strategy for fines. There is one fine rule; its numbers are in Policy. If members had categories with different rules, a fine rule per category might earn an interface; until then it is data.
  • No Observer for “your hold is ready”. Notifications are out of scope. check_in returns who the copy was set aside for, which is what a notifier would need.
  • No Singleton. Each test builds its own Library over its own in-memory store.

The example has two steps:

  • step-1: titles, copies, loans, renewals, fines, one hold per title (FR-1 … FR-9).
  • step-2: the hold queue, the change.

Every rule asks “where is this copy, and who is it for?”, so start with the copy. The tempting first version keeps flags:

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

// Two flags and six fields, all present all the time. Nothing in the type
// says which fields go with which flag, and nothing stops both flags being
// true at once: "on loan and on the hold shelf" can be written down.
struct Copy {
Barcode barcode;
Isbn isbn;
bool on_loan = false;
MemberId borrower; // meaningful only when on_loan
Date due;
bool on_hold_shelf = false;
MemberId held_for; // meaningful only when on_hold_shelf
Date hold_until;
};
// Each caller must remember to set every related field by hand. This one
// does not, and the compiler cannot notice.
void check_in(Copy& copy) {
// Where it goes wrong, first: on_loan is now false, but borrower and due
// still hold the old loan's member (Ana) and date. Any code that reads
// borrower without checking on_loan first gets someone who returned it.
copy.on_loan = false; // forgot: clear borrower and due
// And second: the copy is now "on the hold shelf", but held_for still
// has its default, MemberId{0}, a member who does not exist, and
// hold_until was never set. The member who is waiting is not recorded.
if (someone_waiting(copy.isbn)) copy.on_hold_shelf = true; // forgot held_for
}

This compiles (given a someone_waiting function), and leaves a copy “on the hold shelf” for member 0 with Ana still recorded as its borrower. The corrected version gives each status its own data:

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

copy.hpp
// The three places a copy can be. Each is its own small struct holding
// only the data that makes sense in that place.
// On the open shelf: anyone may borrow it, and there is nothing to record.
struct OnShelf {};
// Out with a member: who has it, when it is due back, and how many times
// the loan has been renewed (it starts at 0).
struct OnLoan {
MemberId member;
Date due;
int renewals = 0;
};
// Set aside for a member who placed a hold. `until` is the last day
// they can collect it.
struct OnHoldShelf {
MemberId member;
Date until;
};
// A std::variant holds exactly one of the listed types at a time, like a
// box with one compartment that can take any one of three shapes. So a
// copy is on the shelf, or on loan, or on the hold shelf, never two at
// once, and the borrower and due date exist only while it is on loan.
// std::holds_alternative<OnLoan>(status) asks which one it holds, and
// std::get_if<OnLoan>(&status) gives a pointer to it, or nullptr if the
// variant holds something else.
using CopyStatus = std::variant<OnShelf, OnLoan, OnHoldShelf>;

Copy then guards the moves between them:

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

copy.cpp
// Each function below first checks that the copy is in a status it may
// leave, and otherwise calls wrong_state (defined just above this part of
// the file). wrong_state throws std::logic_error naming the barcode and
// the action, and is marked [[noreturn]]: it never comes back, so the line
// after `if (...) wrong_state(...)` runs only when the check passed.
// The barcode and ISBN were already checked when they were made; they are
// moved in, and status_ starts as OnShelf{} (see copy.hpp).
Copy::Copy(Barcode barcode, Isbn isbn) : barcode_(std::move(barcode)), isbn_(std::move(isbn)) {}
// Lending is allowed from the open shelf (to anyone), or from the hold
// shelf only to the member it was set aside for.
void Copy::lend(MemberId member, Date due) {
// A pointer to the OnHoldShelf inside status_, or nullptr if the copy
// is in another status.
const auto* held = std::get_if<OnHoldShelf>(&status_);
// `held != nullptr` is tested first: `&&` stops at a false left side,
// so held->member is read only when there is an OnHoldShelf to read.
const bool allowed = std::holds_alternative<OnShelf>(status_) ||
(held != nullptr && held->member == member);
if (!allowed) wrong_state(*this, "lend");
// Assigning a new alternative replaces the old one: the OnHoldShelf (if
// any) is destroyed, so `held` must not be used after this line.
status_ = OnLoan{member, due, 0};
}
// Only a copy on loan can be renewed. The loan is changed in place: the
// borrower stays, the due date moves, and the count goes up by one.
void Copy::renew(Date new_due) {
// Not const: this pointer is used to change the OnLoan inside status_.
auto* loan = std::get_if<OnLoan>(&status_);
if (loan == nullptr) wrong_state(*this, "renew");
loan->due = new_due;
++loan->renewals;
}
// Ends a loan. The caller needs the old loan (who had it, and when it was
// due) to work out a fine, so it is returned by value.
OnLoan Copy::take_back() {
const auto* loan = std::get_if<OnLoan>(&status_);
if (loan == nullptr) wrong_state(*this, "take back");
const OnLoan ended = *loan; // copy it out before the variant changes
// From here the OnLoan that `loan` pointed to no longer exists;
// `ended` is a separate copy, so it is still safe to return.
status_ = OnShelf{};
return ended;
}
// Puts a copy from the open shelf on the hold shelf for one member. A copy
// on loan or already set aside cannot be set aside again.
void Copy::set_aside(MemberId member, Date until) {
if (!std::holds_alternative<OnShelf>(status_)) wrong_state(*this, "set aside");
status_ = OnHoldShelf{member, until};
}
// Takes a copy off the hold shelf (not collected, or the hold cancelled)
// and puts it back on the open shelf.
void Copy::reshelve() {
if (!std::holds_alternative<OnHoldShelf>(status_)) wrong_state(*this, "reshelve");
status_ = OnShelf{};
}
How this code works: The moves a Copy allows

Each function is allowed from one or two statuses, and throws std::logic_error (through wrong_state) from any other:

Function Allowed from Becomes
lend(member, due) OnShelf, or OnHoldShelf for that same member OnLoan{member, due, 0}
renew(new_due) OnLoan the same OnLoan, with due = new_due and renewals one higher
take_back() OnLoan OnShelf; returns the loan that ended
set_aside(member, until) OnShelf OnHoldShelf{member, until}
reshelve() OnHoldShelf OnShelf

How each check works. std::get_if<OnLoan>(&status_) returns a pointer to the OnLoan inside the variant, or nullptr if the variant holds something else. So loan == nullptr means “not on loan”, and wrong_state is called. Because wrong_state never returns, the lines after it can use loan safely.

When a pointer into the variant stays valid. renew changes the OnLoan through the pointer, and the variant keeps holding an OnLoan, so the pointer stays good. take_back and lend assign a different alternative, which destroys the old one. That is why take_back copies the loan into ended first, and why lend does not touch held after its assignment.

M1’s life in the demo, as a chain of these moves: OnShelf, then lend(ana, 23 March), then take_back() on 26 March (back to OnShelf), then set_aside(ben, 29 March) from route, then reshelve() from the morning job on 30 March, then lend(chloe, 20 April), then two renew calls. The third renewal is refused by Library::renew before Copy is asked, because renewals is already 2.

take_back copies the loan out before it assigns OnShelf. The pointer loan points into status_; assigning another alternative destroys the OnLoan it points to, so reading through it afterwards would be undefined behaviour. check_in follows the same rule: it reads the borrower in a short block, before the status changes.

Checking out tries the cheap refusals first and changes one copy:

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

library.cpp
// Lends one copy to one member, due loan_days (21) after `today`. Returns
// ok, or the first reason it refuses; a refusal changes nothing. The
// pattern of every use case here: load copies of the records, check,
// change the local copies, save them back.
Outcome Library::check_out(MemberId id, const Barcode& barcode, Date today) {
// find returns a std::optional: empty if there is no such record.
// `!member` is true when it is empty. member->fines() reads the Member
// inside, like a pointer; it is safe only after that check.
const std::optional<Member> member = members_.find(id);
if (!member) return Outcome::unknown_member;
// Not const: this local copy of the Copy is changed by lend below.
std::optional<Copy> copy = copies_.find(barcode);
if (!copy) return Outcome::unknown_copy;
// The member's checks first: owing 5.00 or more blocks (>=, so exactly
// 5.00 blocks too), and so does having max_loans (5) copies already.
if (member->fines() >= policy_.blocking_fines) return Outcome::fines_owed;
// size() is an unsigned std::size_t and max_loans an int; the cast
// makes both sides the same kind of number, so the compiler does not
// warn about comparing signed with unsigned.
if (copies_.on_loan_to(id).size() >= static_cast<std::size_t>(policy_.max_loans)) {
return Outcome::loan_limit; // INV-2
}
// Then the copy's: out with anyone (this member included) is refused.
if (std::holds_alternative<OnLoan>(copy->status())) return Outcome::on_loan;
// `if (declaration)` declares `held` and enters the block only when it
// is not nullptr, that is, when the copy is on the hold shelf. A copy
// set aside for this member falls through and may be lent.
if (const auto* held = std::get_if<OnHoldShelf>(&copy->status())) {
if (held->member != id) return Outcome::held_for_another; // INV-4
}
// Every check passed, so lend cannot throw here. days{21} is a length
// of time in days; adding it to a Date gives the due date. The change
// is only on the local copy until save stores it.
copy->lend(id, today + days{policy_.loan_days});
copies_.save(*copy);
return Outcome::ok;
}

The member’s checks come before the copy’s status, so a member who owes fines hears that first, whatever copy they picked up. That order is a choice; ac_1_4 fixes it, by trying a copy that is out, so it does not change by accident.

Renewing:

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

library.cpp
// Extends a loan: the new due date is loan_days (21) from `today`, not
// from the old due date. Refused unless the copy is on loan to this
// member, they owe less than 5.00, the loan is not overdue, it has been
// renewed fewer than max_renewals (2) times, and nobody waits for the title.
Outcome Library::renew(MemberId id, const Barcode& barcode, Date today) {
const std::optional<Member> member = members_.find(id);
if (!member) return Outcome::unknown_member;
std::optional<Copy> copy = copies_.find(barcode);
if (!copy) return Outcome::unknown_copy;
// A pointer to the OnLoan inside the local copy's status, or nullptr if
// it is not on loan. `||` stops at a true left side, so loan->member
// is read only when `loan` points at something.
const auto* loan = std::get_if<OnLoan>(&copy->status());
if (loan == nullptr || loan->member != id) return Outcome::not_your_loan;
if (member->fines() >= policy_.blocking_fines) return Outcome::fines_owed;
// `>`, so renewing on the due date itself is allowed.
if (today > loan->due) return Outcome::overdue;
if (loan->renewals >= policy_.max_renewals) return Outcome::renewal_limit;
// A missing title is treated as "nobody waiting"; a title whose hold is
// set means another member is waiting, so the copy must come back.
const std::optional<Title> title = titles_.find(copy->isbn());
if (title && title->hold) return Outcome::holds_waiting;
copy->renew(today + days{policy_.loan_days}); // `loan` is not used after this
copies_.save(*copy);
return Outcome::ok;
}

Every path that frees a copy, whether it was returned, newly added, not collected, or released by a cancelled hold, calls the same function. That is how INV-3 is kept:

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

library.cpp
// Decides where a copy that has just come free goes. The copy must be on
// the open shelf (set_aside throws std::logic_error otherwise); every
// caller makes sure of that first. Both parameters are references to the
// caller's local copies, so route changes those, and the caller saves
// them. `const` at the end means route does not change the Library
// itself. Returns the member the copy was set aside for, or std::nullopt.
std::optional<MemberId> Library::route(Copy& copy, Title& title, Date today) const {
if (!title.hold) return std::nullopt; // stays on the shelf
// Read the waiting member out first: after reset() the optional is
// empty, and *title.hold would then be undefined behaviour.
const MemberId waiting = *title.hold;
title.hold.reset(); // the hold is met, so nobody waits any more
// The member may collect it until hold_days (3) after today, inclusive.
copy.set_aside(waiting, today + days{policy_.hold_days});
return waiting;
}

Holds, cancelling, and the morning job:

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

library.cpp
// A member asks to wait for a title. Allowed only when no copy of it is
// on the open shelf (borrow that instead), the member does not already
// have a copy of it (on loan or set aside), and, in step 1, nobody else
// is waiting. The checks only read; the one change is the hold, saved
// with the title.
Outcome Library::place_hold(MemberId id, const Isbn& isbn) {
// Only whether the member exists matters here: an empty optional is
// false, so !find(...) means "no such member".
if (!members_.find(id)) return Outcome::unknown_member;
std::optional<Title> title = titles_.find(isbn);
if (!title) return Outcome::unknown_title;
// copies_of returns a new vector; the loop keeps it alive while it
// runs. The first copy that gives a reason to refuse ends the search.
for (const Copy& copy : copies_.copies_of(isbn)) {
if (std::holds_alternative<OnShelf>(copy.status())) return Outcome::copy_on_shelf;
// `if (declaration; condition)`: `loan` is declared, then the
// condition is tested, and `loan` exists only inside this if.
// `loan && ...` checks it is not nullptr before reading it.
if (const auto* loan = std::get_if<OnLoan>(&copy.status()); loan && loan->member == id) {
return Outcome::has_a_copy;
}
// The same for a copy already set aside for this member: their
// hold was met, and a copy is waiting for them to collect.
if (const auto* held = std::get_if<OnHoldShelf>(&copy.status());
held && held->member == id) {
return Outcome::has_a_copy;
}
}
// Comparing an optional with a MemberId is true only when the optional
// holds that same id; an empty optional never equals one.
if (title->hold == id) return Outcome::already_held;
// Holds someone else: step 1 has room for only one waiting member.
if (title->hold) return Outcome::hold_taken;
title->hold = id; // stores the id in the optional
titles_.save(*title);
return Outcome::ok;
}
// A member stops waiting. Either they are still waiting (just clear the
// hold), or their hold was already met and a copy is set aside for them
// (put it back and pass it on). Anything else is no_hold.
Outcome Library::cancel_hold(MemberId id, const Isbn& isbn, Date today) {
std::optional<Title> title = titles_.find(isbn);
if (!title) return Outcome::unknown_title;
if (title->hold == id) {
title->hold.reset(); // empty the optional: nobody waits now
titles_.save(*title);
return Outcome::ok;
}
// The hold may already have a copy set aside: free it for the next.
// `Copy copy` (not const Copy&) gives each pass its own copy, which
// this loop changes and saves.
for (Copy copy : copies_.copies_of(isbn)) {
const auto* held = std::get_if<OnHoldShelf>(&copy.status());
if (held != nullptr && held->member == id) {
copy.reshelve(); // back to OnShelf; `held` must not be read now
route(copy, *title, today); // to whoever holds the title now, if anyone
copies_.save(copy);
titles_.save(*title);
return Outcome::ok;
}
}
return Outcome::no_hold;
}
// The morning job. Every copy whose last collection day is before today
// goes back on the shelf and then through route, so it is set aside for
// the next waiting member if there is one. Returns the barcodes of the
// copies it moved, either way.
std::vector<Barcode> Library::expire_holds(Date today) {
std::vector<Barcode> moved;
// on_hold_shelf returns a separate list of copies, taken before the
// loop starts, so saving inside the loop does not disturb the loop.
for (Copy copy : copies_.on_hold_shelf()) {
// `<=`: on the last day itself the copy can still be collected, so
// it is skipped; `continue` moves on to the next copy.
if (today <= std::get<OnHoldShelf>(copy.status()).until) continue;
// Loaded fresh for each copy, so two copies of one title see each
// other's changes to its hold.
std::optional<Title> title = titles_.find(copy.isbn());
if (!title) throw std::logic_error("copy refers to a missing title");
copy.reshelve();
route(copy, *title, today);
copies_.save(copy);
titles_.save(*title);
moved.push_back(copy.barcode());
}
return moved;
}
How this code works: Holds, cancelling, and the morning job

place_hold asks three questions about the title’s copies, one copy at a time, and stops at the first reason to refuse: is this copy on the open shelf (then borrow it), is it on loan to this member, or is it set aside for them (then they already have one)? Only if no copy gives a reason does it look at the title’s hold: this member already waiting is already_held, someone else waiting is hold_taken, and an empty hold is filled with this member and saved.

cancel_hold has two cases. If the member is the one waiting, the hold is cleared. If not, the member’s hold may already have been met: a copy can be on the hold shelf for them, with the title’s hold now empty or held by someone else. Then that copy goes back on the shelf and through route, so it passes to whoever waits now.

expire_holds takes the list of copies on the hold shelf once, before its loop starts. A copy is skipped while today is on or before its last day. Otherwise it goes back on the shelf, through route, and is saved, and its barcode goes in the result.

A worked example, from the test ac_4_3_an_expired_copy_goes_to_a_member_who_held_it_since:

Call M1 afterwards Moss’s hold afterwards
check_out(ana, M1, 1 March) OnLoan{ana, 22 March, 0} empty
place_hold(ben, moss) unchanged ben
check_in(M1, 10 March) OnHoldShelf{ben, 13 March} empty: route met it
place_hold(chloe, moss) unchanged chloe
expire_holds(14 March) OnHoldShelf{chloe, 17 March} empty: route met it

Chloe’s hold is accepted because M1 is set aside for Ben, not for her, and is not on the open shelf. On 14 March, 14 is after 13, so M1 is not skipped: reshelve puts it on the open shelf, and route at once sets it aside for Chloe until 14 + 3 = 17 March. The result is {M1}.

expire_holds takes today and compares it with each copy’s last day. It does not know what time it is. The caller, a scheduler in the real branch and a test here, decides when “the next morning” is.

Every function that needs today’s date takes it as a parameter. A test can check out on 1 March and check in on 25 March in two lines, and a fine that depends on the date is a plain function of its inputs. The same approach passes Time now in the parking lot. The cost is one parameter; the alternative, reading the system clock inside the rules, makes the fine tests depend on the day they run.

The statuses of a copy and the calls that move it between them
Text description of the diagram

A new copy starts on the shelf, or on the hold shelf if a member is waiting for its title. From the shelf, check_out moves it to OnLoan. renew keeps it in OnLoan with a new due date. check_in moves it back to the shelf if no one waits, or to the hold shelf for the member who waits. From the hold shelf, check_out by the member it is for moves it to OnLoan. If that member does not collect it in time, or cancels, it goes back to the shelf when no one else waits, or stays on the hold shelf for the next member who does.

Diagram source (Mermaid)
stateDiagram-v2
[*] --> OnShelf : add_copy [no one waiting]
[*] --> OnHoldShelf : add_copy [a member waiting]
OnShelf --> OnLoan : check_out
OnLoan --> OnLoan : renew
OnLoan --> OnShelf : check_in [no one waiting]
OnLoan --> OnHoldShelf : check_in [a member waiting]
OnHoldShelf --> OnLoan : check_out [by that member]
OnHoldShelf --> OnShelf : expired or cancelled [no one else waiting]
OnHoldShelf --> OnHoldShelf : expired or cancelled [another member waiting]
Checking in M1 on 26 March, three days late, with Ben waiting
Text description of the diagram

The desk calls check_in for M1 on 26 March. The Library finds the copy, which is on loan to Ana and was due on 23 March. It finds the title, which Ben is waiting for, and finds Ana, who owes nothing. On local copies it ends the loan, charges Ana 0.75 for three days, and routes the copy: it is set aside for Ben until 29 March and Ben’s hold is cleared. Only then does it save the copy, the title, and Ana. It tells the desk: ok, fine 0.75, set aside for Ben.

Diagram source (Mermaid)
sequenceDiagram
participant D as desk
participant L as Library
participant C as CopyRepository
participant T as TitleRepository
participant M as MemberRepository
D->>L: check_in(M1, 26 March)
L->>C: find(M1)
C-->>L: copy, on loan to Ana, due 23 March
L->>T: find(Moss)
T-->>L: title, Ben waiting
L->>M: find(Ana)
M-->>L: Ana, owes 0.00
L->>L: take_back, 3 days late, Ana owes 0.75
L->>L: route, set aside for Ben until 29 March
L->>C: save(copy)
L->>T: save(title)
L->>M: save(Ana)
L-->>D: ok, fine 0.75, set aside for Ben

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

main.cpp
// The month from the page, played in order. Each line of output comes from
// say(date, what, outcome), a helper above this part of the file that
// prints "date what -> outcome in words"; on(March, 2) makes the Date
// 2 March 2026. The expected output is shown below this code.
int main() {
// The three stores are declared before `lib`, so they are created first
// and destroyed last: the Library keeps references to them (it does not
// own them), and they must outlive it.
InMemoryTitles titles;
InMemoryCopies copies;
InMemoryMembers members;
Library lib(titles, copies, members); // no Policy given: the defaults
const Isbn sail("9780000000001");
const Isbn moss("9780000000002");
const MemberId ana{1};
const MemberId ben{2};
const MemberId chloe{3};
lib.add_title(sail, "Learning to Sail", "R. Hale");
lib.add_title(moss, "A Field Guide to Moss", "T. Brandt");
lib.add_copy(Barcode("S1"), sail, on(March, 1));
lib.add_copy(Barcode("S2"), sail, on(March, 1));
lib.add_copy(Barcode("M1"), moss, on(March, 1));
lib.add_member(ana, "Ana");
lib.add_member(ben, "Ben");
lib.add_member(chloe, "Chloe");
// Staff setup: two titles, three copies, three members. Moss has one
// copy, M1, so a second reader must wait for it.
std::cout << "-- loans and a hold\n";
say(on(March, 2), "Ana checks out M1", lib.check_out(ana, Barcode("M1"), on(March, 2)));
say(on(March, 2), "Ana checks out S1", lib.check_out(ana, Barcode("S1"), on(March, 2)));
// loans_of returns a vector of copies, kept alive for the whole loop.
// Each is on loan, so std::get<OnLoan> (which throws if the variant
// holds anything else) is safe, and .due reads the due date.
for (const Copy& c : lib.loans_of(ana)) {
std::cout << " " << c.barcode().str() << " due "
<< format_date(std::get<OnLoan>(c.status()).due) << '\n';
}
say(on(March, 3), "Ben checks out M1", lib.check_out(ben, Barcode("M1"), on(March, 3)));
say(on(March, 3), "Ben holds Moss", lib.place_hold(ben, moss));
say(on(March, 3), "Chloe holds Moss", lib.place_hold(chloe, moss));
say(on(March, 3), "Ben holds Sail", lib.place_hold(ben, sail));
say(on(March, 20), "Ana renews M1", lib.renew(ana, Barcode("M1"), on(March, 20)));
std::cout << "-- a late return goes to the hold shelf\n";
// Three days late (due 23 March), and Ben is waiting: the verification trace.
const CheckIn back = lib.check_in(Barcode("M1"), on(March, 26));
std::cout << format_date(on(March, 26)) << " M1 returned -> " << describe(back.outcome)
<< ", fine " << format_cents(back.fine);
// set_aside_for is an optional MemberId: true here if the copy went to
// a waiting member. find returns an optional Copy, and -> reaches the
// Copy inside (M1 exists, so it is not empty); `held` is a copy of its
// OnHoldShelf, taken before that temporary optional goes away at the
// end of the line. *back.set_aside_for reads the id out of the optional.
if (back.set_aside_for) {
const OnHoldShelf held = std::get<OnHoldShelf>(copies.find(Barcode("M1"))->status());
std::cout << ", set aside for " << members.find(*back.set_aside_for)->name() << " until "
<< format_date(held.until);
}
std::cout << '\n';
say(on(March, 27), "Chloe checks out M1", lib.check_out(chloe, Barcode("M1"), on(March, 27)));
// Ben had until 29 March. On the 30th the morning job puts M1 back;
// nobody else is waiting, so it goes to the open shelf.
std::cout << "-- not collected\n";
for (const Barcode& b : lib.expire_holds(on(March, 30))) {
std::cout << format_date(on(March, 30)) << " morning job: " << b.str()
<< " back on the shelf\n";
}
say(on(March, 30), "Chloe checks out M1", lib.check_out(chloe, Barcode("M1"), on(March, 30)));
// Chloe's loan was due 20 April. Each renewal runs 21 days from the day
// it is made (to 6 May, then 22 May); the third is over the limit of 2.
std::cout << "-- the renewal limit\n";
say(on(April, 15), "Chloe renews M1", lib.renew(chloe, Barcode("M1"), on(April, 15)));
say(on(May, 1), "Chloe renews M1", lib.renew(chloe, Barcode("M1"), on(May, 1)));
say(on(May, 20), "Chloe renews M1", lib.renew(chloe, Barcode("M1"), on(May, 20)));
// S1 was due 23 March and comes back 63 days late: 63 times 25 = 1575
// cents, capped at 1000. With the earlier 0.75, Ana owes 10.75, which
// blocks borrowing; after paying 6.00 Ana owes 4.75 and may borrow.
std::cout << "-- fines\n";
const CheckIn late = lib.check_in(Barcode("S1"), on(May, 25));
std::cout << format_date(on(May, 25)) << " S1 returned -> " << describe(late.outcome)
<< ", fine " << format_cents(late.fine) << " (capped)\n";
std::cout << " Ana owes " << format_cents(members.find(ana)->fines()) << '\n';
say(on(May, 25), "Ana checks out S2", lib.check_out(ana, Barcode("S2"), on(May, 25)));
say(on(May, 25), "Ana pays 6.00", lib.pay(ana, 600));
std::cout << " Ana owes " << format_cents(members.find(ana)->fines()) << '\n';
say(on(May, 25), "Ana checks out S2", lib.check_out(ana, Barcode("S2"), on(May, 25)));
}
Expected output
-- loans and a hold
2026-03-02 Ana checks out M1 -> ok
2026-03-02 Ana checks out S1 -> ok
M1 due 2026-03-23
S1 due 2026-03-23
2026-03-03 Ben checks out M1 -> refused, that copy is out
2026-03-03 Ben holds Moss -> ok
2026-03-03 Chloe holds Moss -> refused, another member is already waiting
2026-03-03 Ben holds Sail -> refused, a copy is on the shelf
2026-03-20 Ana renews M1 -> refused, another member is waiting
-- a late return goes to the hold shelf
2026-03-26 M1 returned -> ok, fine 0.75, set aside for Ben until 2026-03-29
2026-03-27 Chloe checks out M1 -> refused, set aside for another member
-- not collected
2026-03-30 morning job: M1 back on the shelf
2026-03-30 Chloe checks out M1 -> ok
-- the renewal limit
2026-04-15 Chloe renews M1 -> ok
2026-05-01 Chloe renews M1 -> ok
2026-05-20 Chloe renews M1 -> refused, renewed the most times allowed
-- fines
2026-05-25 S1 returned -> ok, fine 10.00 (capped)
Ana owes 10.75
2026-05-25 Ana checks out S2 -> refused, fines owed
2026-05-25 Ana pays 6.00 -> ok
Ana owes 4.75
2026-05-25 Ana checks out S2 -> ok

How to read it:

  1. Ana borrows both M1 and S1 on 2 March; both are due 23 March (AC-1.1). Ben finds M1 out (AC-1.2) and holds the title. Chloe cannot also hold it in step 1 (AC-4.2). Ben cannot hold Learning to Sail, because S2 is on the shelf (AC-4.1). Ana cannot renew M1, because Ben waits (AC-2.2).
  2. M1 comes back three days late: 0.75, and it goes to the hold shelf for Ben until 29 March (AC-3.2, AC-3.3). Chloe cannot take it (AC-1.5).
  3. Ben does not come. On 30 March the morning job puts M1 back on the shelf, and Chloe borrows it (AC-4.3).
  4. Chloe renews twice and is refused the third time (AC-2.1).
  5. S1 comes back 63 days late; the fine is capped at 10.00 (AC-3.2). Ana owes 10.75 and cannot borrow; after paying 6.00, Ana owes 4.75, below the 5.00 block, and can (AC-1.4).

The tests are in step-1/tests/test_step1.cpp, named after the acceptance criteria. Each builds a small library over in-memory repositories and calls the same functions the desk would:

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

test_step1.cpp
// Names shared by every test: three members and two ISBNs.
const MemberId ana{1};
const MemberId ben{2};
const MemberId chloe{3};
const Isbn sail("9780000000001");
const Isbn moss("9780000000002");
// march(5) is 5 March 2026. `2026y / March / day{d}` is how <chrono>
// writes a calendar date; sys_days{...} turns it into a Date.
Date march(unsigned d) { return sys_days{2026y / March / std::chrono::day{d}}; }
// A library with two titles: "sail" has copies S1 and S2, "moss" has M1.
// Each test makes its own Rig, so no test can see another's changes.
// The stores are declared before `lib`, so they are built first and
// destroyed after it: the Library only refers to them.
struct Rig {
InMemoryTitles titles;
InMemoryCopies copies;
InMemoryMembers members;
Library lib{titles, copies, members};
// Every copy is added on 1 March, with nobody waiting: all on the shelf.
Rig() {
lib.add_title(sail, "Learning to Sail", "R. Hale");
lib.add_title(moss, "A Field Guide to Moss", "T. Brandt");
lib.add_copy(Barcode("S1"), sail, march(1));
lib.add_copy(Barcode("S2"), sail, march(1));
lib.add_copy(Barcode("M1"), moss, march(1));
lib.add_member(ana, "Ana");
lib.add_member(ben, "Ben");
lib.add_member(chloe, "Chloe");
}
// Small readers that look in the stores, so a test checks what was
// saved, not only what a function returned. .value() reads what is in
// an optional, and throws std::bad_optional_access if it is empty, so a
// missing record fails the test loudly instead of being read as junk.
// The saved status of a copy. It is returned by value (copied), which
// matters: the Copy that find returned is a temporary that is gone
// after this line, so a reference to its status would dangle.
CopyStatus status(const char* barcode) const {
return copies.find(Barcode(barcode)).value().status();
}
// A template: rig.as<OnLoan>("S1") gives the copy's OnLoan if it is on
// loan, and std::nullopt if it is anywhere else. State is the type
// named in the angle brackets.
template <typename State>
std::optional<State> as(const char* barcode) const {
const CopyStatus now = status(barcode);
if (const auto* s = std::get_if<State>(&now)) return *s;
return std::nullopt;
}
// What a member owes, and who (if anyone) waits for a title, as saved.
Cents fines(MemberId id) const { return members.find(id).value().fines(); }
std::optional<MemberId> hold(const Isbn& isbn) const { return titles.find(isbn).value().hold; }
};

The test reads results back through the repositories, so it checks what was saved, not just what a function returned. A forgotten save is a failing test.

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

test_step1.cpp
// LLD_TEST(name) defines one test; the name is the acceptance criterion it
// checks (ac_1_1 is AC-1.1). LLD_CHECK(condition) records a failure if the
// condition is false, and LLD_CHECK_EQ(actual, expected) does the same for
// two values and prints both when they differ. They come from the site's
// small test header, lld_test.hpp. A test goes on after a failed check, so
// one run reports every check that failed.
// Ana borrows S1 on 2 March: it is saved as on loan to Ana, due 23 March,
// and it is her only loan.
LLD_TEST(ac_1_1_a_copy_on_the_shelf_is_lent_for_21_days) {
Rig rig;
LLD_CHECK(rig.lib.check_out(ana, Barcode("S1"), march(2)) == Outcome::ok);
const std::optional<OnLoan> loan = rig.as<OnLoan>("S1");
// `loan &&` first: if S1 were not on loan, loan->member would read an
// empty optional. With it, the check simply fails.
LLD_CHECK(loan && loan->member == ana);
LLD_CHECK(loan && loan->due == march(23));
LLD_CHECK_EQ(rig.lib.loans_of(ana).size(), std::size_t{1});
}
// A copy on loan is refused to anyone, including the member who has it.
// (check_out's result is ignored on lines that only set the scene.)
LLD_TEST(ac_1_2_a_copy_that_is_out_is_refused) {
Rig rig;
rig.lib.check_out(ana, Barcode("S1"), march(2));
LLD_CHECK(rig.lib.check_out(ben, Barcode("S1"), march(3)) == Outcome::on_loan);
LLD_CHECK(rig.lib.check_out(ana, Barcode("S1"), march(3)) == Outcome::on_loan);
}
// Six more copies of moss, X1 to X6. Ana borrows five; the sixth is
// refused and stays on the shelf. `std::to_string(i)` makes "1", "2", ...
LLD_TEST(ac_1_3_the_sixth_loan_is_refused) {
Rig rig;
for (int i = 1; i <= 6; ++i) {
rig.lib.add_copy(Barcode("X" + std::to_string(i)), moss, march(1));
}
for (int i = 1; i <= 5; ++i) {
LLD_CHECK(rig.lib.check_out(ana, Barcode("X" + std::to_string(i)), march(2)) ==
Outcome::ok);
}
LLD_CHECK(rig.lib.check_out(ana, Barcode("X6"), march(2)) == Outcome::loan_limit);
LLD_CHECK(std::holds_alternative<OnShelf>(rig.status("X6")));
}
// Ana returns S1 21 days late (525 cents). Owing 5.25 blocks her, even for
// a copy that is out (the member's checks come first). Paying 0.25 leaves
// exactly 5.00, still blocked; paying 0.01 more leaves 4.99, allowed.
LLD_TEST(ac_1_4_owing_5_00_stops_borrowing_until_paid_below_it) {
Rig rig;
rig.lib.check_out(ana, Barcode("S1"), march(1)); // due 22 March
rig.lib.check_in(Barcode("S1"), sys_days{2026y / April / 12}); // 21 days late
LLD_CHECK_EQ(rig.fines(ana), Cents{525});
LLD_CHECK(rig.lib.check_out(ana, Barcode("M1"), march(30)) == Outcome::fines_owed);
rig.lib.check_out(ben, Barcode("S2"), march(30));
// The member's checks come first, so a copy that is out still says fines_owed.
LLD_CHECK(rig.lib.check_out(ana, Barcode("S2"), march(30)) == Outcome::fines_owed);
LLD_CHECK(rig.lib.pay(ana, 25) == Outcome::ok); // owes 5.00: still blocked
LLD_CHECK(rig.lib.check_out(ana, Barcode("M1"), march(30)) == Outcome::fines_owed);
LLD_CHECK(rig.lib.pay(ana, 1) == Outcome::ok); // owes 4.99
LLD_CHECK(rig.lib.check_out(ana, Barcode("M1"), march(30)) == Outcome::ok);
}
// M1 comes back while Ben waits, so it is set aside for him. Ben cannot
// hold again (a copy waits for him), Chloe cannot borrow it, Ben can.
LLD_TEST(ac_1_5_a_copy_set_aside_is_lent_only_to_its_member) {
Rig rig;
rig.lib.check_out(ana, Barcode("M1"), march(2));
LLD_CHECK(rig.lib.place_hold(ben, moss) == Outcome::ok);
rig.lib.check_in(Barcode("M1"), march(5));
LLD_CHECK(rig.lib.place_hold(ben, moss) == Outcome::has_a_copy); // set aside counts
LLD_CHECK(rig.lib.check_out(chloe, Barcode("M1"), march(5)) == Outcome::held_for_another);
LLD_CHECK(rig.lib.check_out(ben, Barcode("M1"), march(6)) == Outcome::ok);
}
// Member 99 and barcode Z9 do not exist: refused as values, no exception.
LLD_TEST(ac_1_6_unknown_members_and_copies_are_refused) {
Rig rig;
LLD_CHECK(rig.lib.check_out(MemberId{99}, Barcode("S1"), march(2)) ==
Outcome::unknown_member);
LLD_CHECK(rig.lib.check_out(ana, Barcode("Z9"), march(2)) == Outcome::unknown_copy);
LLD_CHECK(rig.lib.check_in(Barcode("Z9"), march(2)).outcome == Outcome::unknown_copy);
}

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

test_step1.cpp
// S1 is due 22 March and comes back on 22 March: no fine, nobody waiting,
// back on the shelf, and Ana has no loans left.
LLD_TEST(ac_3_1_a_copy_back_on_time_costs_nothing) {
Rig rig;
rig.lib.check_out(ana, Barcode("S1"), march(1));
const CheckIn r = rig.lib.check_in(Barcode("S1"), march(22)); // the due date itself
LLD_CHECK(r.outcome == Outcome::ok);
LLD_CHECK_EQ(r.fine, Cents{0});
LLD_CHECK(!r.set_aside_for.has_value());
LLD_CHECK(std::holds_alternative<OnShelf>(rig.status("S1")));
LLD_CHECK(rig.lib.loans_of(ana).empty());
}
// Three days late costs 75 cents. S2, out on 1 March and back on 30 June,
// is 100 days late: 2500 cents, capped at 1000. Ana owes the sum, 1075.
LLD_TEST(ac_3_2_late_returns_cost_0_25_a_day_up_to_10_00) {
Rig rig;
rig.lib.check_out(ana, Barcode("S1"), march(1)); // due 22 March
LLD_CHECK_EQ(rig.lib.check_in(Barcode("S1"), march(25)).fine, Cents{75});
rig.lib.check_out(ana, Barcode("S2"), march(1));
const CheckIn r = rig.lib.check_in(Barcode("S2"), sys_days{2026y / June / 30});
LLD_CHECK_EQ(r.fine, Cents{1000}); // 100 days late, capped
LLD_CHECK_EQ(rig.fines(ana), Cents{1075});
}
// Ben waits for moss. When M1 comes back on 10 March it is set aside for
// Ben until 13 March (3 days), and the title's hold is cleared.
LLD_TEST(ac_3_3_a_returned_copy_is_set_aside_for_the_member_waiting) {
Rig rig;
rig.lib.check_out(ana, Barcode("M1"), march(1));
rig.lib.place_hold(ben, moss);
const CheckIn r = rig.lib.check_in(Barcode("M1"), march(10));
LLD_CHECK(r.set_aside_for == ben); // optional == value: holds ben
const std::optional<OnHoldShelf> held = rig.as<OnHoldShelf>("M1");
LLD_CHECK(held && held->member == ben && held->until == march(13));
LLD_CHECK(!rig.hold(moss).has_value()); // the hold has been met
}
// S1 is on the shelf, so checking it in is refused.
LLD_TEST(ac_3_4_a_copy_that_was_not_out_is_refused) {
Rig rig;
LLD_CHECK(rig.lib.check_in(Barcode("S1"), march(2)).outcome == Outcome::not_on_loan);
}

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

test_step1.cpp
// A hold is refused while either copy of sail is on the shelf, and
// accepted once both are out. An unknown member is refused too.
LLD_TEST(ac_4_1_a_hold_is_placed_only_when_no_copy_is_on_the_shelf) {
Rig rig;
LLD_CHECK(rig.lib.place_hold(ben, sail) == Outcome::copy_on_shelf);
rig.lib.check_out(ana, Barcode("S1"), march(2));
LLD_CHECK(rig.lib.place_hold(ben, sail) == Outcome::copy_on_shelf); // S2 is in
rig.lib.check_out(chloe, Barcode("S2"), march(2));
LLD_CHECK(rig.lib.place_hold(MemberId{99}, sail) == Outcome::unknown_member);
LLD_CHECK(rig.lib.place_hold(ben, sail) == Outcome::ok);
}
// With M1 out to Ana: Ana cannot hold what she has, Ben can, Ben cannot
// hold twice, Chloe cannot join (step 1 has room for one), and an ISBN
// that is not in the catalogue is refused.
LLD_TEST(ac_4_2_one_member_waits_per_title) {
Rig rig;
rig.lib.check_out(ana, Barcode("M1"), march(2));
LLD_CHECK(rig.lib.place_hold(ana, moss) == Outcome::has_a_copy);
LLD_CHECK(rig.lib.place_hold(ben, moss) == Outcome::ok);
LLD_CHECK(rig.lib.place_hold(ben, moss) == Outcome::already_held);
LLD_CHECK(rig.lib.place_hold(chloe, moss) == Outcome::hold_taken);
LLD_CHECK(rig.lib.place_hold(ben, Isbn("9780000000099")) == Outcome::unknown_title);
}
// Set aside for Ben until 13 March. The morning job on the 13th leaves it
// (the last day counts); on the 14th it moves M1 back to the shelf and
// returns its barcode, and Chloe can borrow it.
LLD_TEST(ac_4_3_a_copy_not_collected_in_time_goes_back_the_next_morning) {
Rig rig;
rig.lib.check_out(ana, Barcode("M1"), march(1));
rig.lib.place_hold(ben, moss);
rig.lib.check_in(Barcode("M1"), march(10)); // set aside until 13 March
LLD_CHECK(rig.lib.expire_holds(march(13)).empty());
const std::vector<Barcode> moved = rig.lib.expire_holds(march(14));
LLD_CHECK(moved == std::vector<Barcode>{Barcode("M1")});
LLD_CHECK(std::holds_alternative<OnShelf>(rig.status("M1")));
LLD_CHECK(rig.lib.check_out(chloe, Barcode("M1"), march(14)) == Outcome::ok);
}
// Chloe places a hold while M1 is set aside for Ben (no copy is on the
// shelf, and Ben's hold was already met, so the title is free). When Ben's
// time runs out, M1 is set aside for Chloe, until 14 + 3 = 17 March.
LLD_TEST(ac_4_3_an_expired_copy_goes_to_a_member_who_held_it_since) {
Rig rig;
rig.lib.check_out(ana, Barcode("M1"), march(1));
rig.lib.place_hold(ben, moss);
rig.lib.check_in(Barcode("M1"), march(10)); // set aside for Ben
LLD_CHECK(rig.lib.place_hold(chloe, moss) == Outcome::ok); // no copy on the shelf
rig.lib.expire_holds(march(14));
const std::optional<OnHoldShelf> held = rig.as<OnHoldShelf>("M1");
LLD_CHECK(held && held->member == chloe && held->until == march(17));
}
// Three cancels. First, a plain hold: it is cleared, and cancelling again
// is no_hold. Second, a hold already met: the copy set aside for Ben goes
// back to the shelf. Third, the same while Chloe waits: the copy passes
// to Chloe instead.
LLD_TEST(ac_4_4_cancelling_a_hold_frees_it_and_any_copy_set_aside) {
Rig rig;
rig.lib.check_out(ana, Barcode("M1"), march(1));
rig.lib.place_hold(ben, moss);
LLD_CHECK(rig.lib.cancel_hold(ben, moss, march(2)) == Outcome::ok);
LLD_CHECK(!rig.hold(moss).has_value());
LLD_CHECK(rig.lib.cancel_hold(ben, moss, march(2)) == Outcome::no_hold);
rig.lib.place_hold(ben, moss);
rig.lib.check_in(Barcode("M1"), march(10)); // set aside for Ben
LLD_CHECK(rig.lib.cancel_hold(ben, moss, march(11)) == Outcome::ok);
LLD_CHECK(std::holds_alternative<OnShelf>(rig.status("M1")));
rig.lib.check_out(ana, Barcode("M1"), march(12));
rig.lib.place_hold(ben, moss);
rig.lib.check_in(Barcode("M1"), march(13)); // set aside for Ben again
LLD_CHECK(rig.lib.place_hold(chloe, moss) == Outcome::ok); // Ben's hold was met
LLD_CHECK(rig.lib.cancel_hold(ben, moss, march(14)) == Outcome::ok);
const std::optional<OnHoldShelf> held = rig.as<OnHoldShelf>("M1");
LLD_CHECK(held && held->member == chloe && held->until == march(17)); // passed on
}
// A new copy, M2, added while Ben waits for moss, goes straight to the
// hold shelf for Ben, not to the open shelf.
LLD_TEST(ac_4_5_a_new_copy_of_a_held_title_goes_to_the_member_waiting) {
Rig rig;
rig.lib.check_out(ana, Barcode("M1"), march(1));
rig.lib.place_hold(ben, moss);
rig.lib.add_copy(Barcode("M2"), moss, march(4));
const std::optional<OnHoldShelf> held = rig.as<OnHoldShelf>("M2");
LLD_CHECK(held && held->member == ben && held->until == march(7));
}

The renewal and fine tests are in the renew-tests and fine-tests regions of the same file. The boundaries are tested on purpose: the due date itself is not late, the last day on the hold shelf is not expired, and owing exactly 5.00 blocks.

Invariants. One test runs sixty days with three members, four copies, holds, returns, cancels, payments, and the morning job. After every day it checks INV-2, INV-3, and INV-5. It also checks that the days really reached set-asides, fines, and expiries, because a mixed test that never placed a hold would check INV-3 against nothing. (An earlier draft of this test did exactly that: with seven copies, no title ever ran out.) The same weakness remains for INV-2: with four copies, no member can reach five loans in this test, so INV-2 rests on ac_1_3 alone.

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

test_step1.cpp
// Sixty days of borrowing, returning, holds, and the morning job, with
// three members and four copies, so that copies run out, holds are
// placed and met, and some returns are late. After each day: no one has
// more than five loans (INV-2), no title with a member waiting has a
// copy on the shelf (INV-3), and no one owes a negative amount (INV-5).
LLD_TEST(inv_2_3_and_5_hold_through_sixty_days) {
Rig rig;
rig.lib.add_copy(Barcode("M2"), moss, march(1)); // a fourth copy
const std::vector<MemberId> people{ana, ben, chloe};
const std::vector<std::string> codes{"S1", "S2", "M1", "M2"};
// Counters that prove the days reached the interesting cases.
int set_aside = 0;
int fined = 0;
int expired = 0;
Date today = march(1);
// Day number `d` runs 0 to 59; `today` moves on by one day with it (the
// part after the second `;` runs at the end of every pass).
for (std::size_t d = 0; d < 60; ++d, today += days{1}) {
// `%` is the remainder after division. `d % 3` cycles 0, 1, 2, 0, ...
// so the members take turns. `(d * 3) % 4` cycles 0, 3, 2, 1, so the
// copy tried each day goes S1, M2, M1, S2, S1, ... Many of these
// tries are refused (the copy is out, or set aside); that is fine,
// because the checks below must hold whatever happened.
const MemberId who = people[d % 3];
rig.lib.check_out(who, Barcode(codes[(d * 3) % 4]), today);
// On odd days the next member in turn asks for a hold: moss when
// `d % 4` is 1 (days 1, 5, 9, ...), sail on the others (3, 7, 11, ...).
if (d % 2 == 1) rig.lib.place_hold(people[(d + 1) % 3], d % 4 == 1 ? moss : sail);
if (d % 7 == 2) { // each copy comes back about every 28 days
// Days 2, 9, 16, 23, ...; `(d * 7) % 4` picks M1, M2, S1, S2 in turn.
const CheckIn r = rig.lib.check_in(Barcode(codes[(d * 7) % 4]), today);
if (r.set_aside_for) ++set_aside;
if (r.fine > 0) ++fined;
}
// Now and then a member cancels a hold on moss (days 7, 18, 29, ...).
if (d % 11 == 7) rig.lib.cancel_hold(people[(d + 2) % 3], moss, today);
// The morning job runs every day; count the copies it moved.
expired += static_cast<int>(rig.lib.expire_holds(today).size());
// Every ninth day (8, 17, 26, ...) today's member pays off everything.
if (d % 9 == 8 && rig.fines(who) > 0) rig.lib.pay(who, rig.fines(who));
// The invariants, checked after every day. INV-2 and INV-5 for each
// member (5u is 5 as an unsigned number, the same kind as size()):
for (const MemberId id : people) {
LLD_CHECK(rig.lib.loans_of(id).size() <= 5u);
LLD_CHECK(rig.fines(id) >= 0);
}
// INV-3: if anyone waits for a title, none of its copies may be on
// the open shelf. `continue` skips a title nobody waits for.
for (const Isbn& isbn : {sail, moss}) {
if (!rig.hold(isbn)) continue;
for (const Copy& c : rig.copies.copies_of(isbn)) {
LLD_CHECK(!std::holds_alternative<OnShelf>(c.status()));
}
}
}
// The days really reach set-asides, fines, and expiry (4, 3, and 4
// when this was written); a mix that never did would check little.
LLD_CHECK(set_aside > 0 && fined > 0 && expired > 0);
}
How this code works: The sixty-day test

Each pass of the loop is one day, d from 0 to 59, with today from 1 March. The remainders (%) give a fixed schedule that is easy to repeat and mixes every kind of event. These are the first ten days, as attempts: many are refused (a copy is already out, a copy is on the shelf so no hold is needed), and that is expected.

d Date What the day tries
0 1 March Ana borrows S1
1 2 March Ben borrows M2; Chloe holds moss
2 3 March Chloe borrows M1; M1 is checked in
3 4 March Ana borrows S2; Ben holds sail
4 5 March Ben borrows S1
5 6 March Chloe borrows M2; Ana holds moss
6 7 March Ana borrows M1
7 8 March Ben borrows S2; Chloe holds sail; Ana cancels her hold on moss
8 9 March Chloe borrows S1; Chloe pays off what she owes, if anything
9 10 March Ana borrows M2; Ben holds moss; M2 is checked in

Every day also runs the morning job, expire_holds. After all of that, the test checks the three invariants against what is saved: nobody has more than five loans, nobody owes less than zero, and no title that someone waits for has a copy on the open shelf.

The last check is about the test itself. The counters record how often a returned copy was set aside, a return was fined, and the morning job moved a copy. If any of them stayed at zero, the schedule would never have reached that kind of event, and the invariant checks would have been run against days where nothing interesting happened. So each counter must be above zero at the end.

Did the tests check enough? library.cpp was changed by hand in twenty-two small ways, one at a time. Thirteen came first: allowing a sixth loan, removing the fine cap, a day of grace, lending a set-aside copy to anyone, a new copy ignoring a hold, renewing despite a hold, renewing when overdue, expiring a hold on its last day, holding with a copy on the shelf, blocking only above 5.00, renewing from the due date, not clearing a met hold, and not saving the fine. The review added nine more, and four of them passed every test: checking the copy before the member, renewing despite fines, holding a title whose copy is already set aside for the same member, and cancelling a set-aside hold without passing the copy on. Tests for those four were added to ac_1_4, ac_1_5, ac_4_4, and a new ac_2_2 renewal test. Now each of the twenty-two makes at least one test fail.

Run them with:

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

The example runs in one process with one thread, and each test owns its store. The branch will not: two desks and a kiosk will share the city’s database.

  1. The lost update. Both desks scan M1 at the same moment. Each find returns OnShelf; each check_out saves OnLoan for its own member. The second save wins, and the first member walks out with a book the system says the second has. A lock inside Library would not help, because the two desks are separate processes. The database must refuse the second save: a version number on each record, checked on save, or a row lock taken by find inside a transaction. See the lost update.
  2. A rule across records. Ana has four loans and checks out at the desk and the kiosk at once. Each counts four, each allows the fifth, and Ana has six (INV-2 broken). A version on the copy does not catch this, because the two copies are different records. The member’s record must take part: lock it, or bump a version on it, in the same transaction as the loan.
  3. The morning job and the desk. If the job runs while the branch is open, it can expire a set-aside copy at the moment its member collects it. Running it before opening, as assumed, avoids the question; otherwise it needs the same versions.
  4. The invariant across a title and its copies. Ben places a hold on Moss at the desk while M1 is checked in at the kiosk. place_hold reads the copies and sees none on the shelf; check_in reads the title and sees no hold, so it shelves M1. Then place_hold saves the hold. Ben now waits for a title whose copy sits on the open shelf: INV-3 is broken, and no one will ever set M1 aside for Ben. Both functions save the title, so a version on the title record catches it: the second save is refused and that use case is tried again.

The paper hold card has gone, and members complain that they cannot queue for a popular book.

“Let any number of members wait for a title, first come, first served. Show them their place in the queue.”

New and changed requirements:

  • FR-5 (changed) A member places a hold on a title when no copy is on the shelf. Any number of members may wait; each waits at most once per title.
  • FR-10 A member can see their place in the queue for a title.
  • FR-11 A copy that comes free goes to the member who has waited longest. If it is not collected in time, or the hold is cancelled, it goes to the next member.

UC-6 The hold queue.

  • AC-6.1 Copies go to waiting members in the order they asked.
  • AC-6.2 A member waits at most once per title, and can see their place (1 is next).
  • AC-6.3 A copy not collected goes to the next member waiting.
  • AC-6.4 Cancelling a hold whose copy is set aside passes the copy to the next member.
  • AC-6.5 Leaving the queue moves the others up.

The rule “a member waits at most once” is new, and it belongs to the queue, not to its callers. The queue becomes a small class with that rule inside:

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

title.hpp
// Step 2: the members waiting for one title, in the order they asked.
// The rule "a member waits at most once per title" is the queue's own,
// so it lives here and not in every caller.
// First come, first served: new members join at the back, and the front
// member is served first. Each function answers with a value (true or
// false, or an optional) instead of throwing, because "already waiting"
// is an ordinary answer at the desk. It is copied with its Title.
class HoldQueue {
public:
// False if the member is already waiting.
// position(member) is an optional: it converts to true when the member
// has a place, so this refuses a second place for the same member.
bool add(MemberId member) {
if (position(member)) return false;
waiting_.push_back(member); // joins at the back
return true;
}
// False if the member was not waiting.
// std::find walks from the front and returns an iterator (a position)
// at the first match, or end() if there is none. erase removes that
// one entry, and everyone behind it moves up one place.
bool remove(MemberId member) {
const auto it = std::find(waiting_.begin(), waiting_.end(), member);
if (it == waiting_.end()) return false;
waiting_.erase(it);
return true;
}
// The member who has waited longest, now served; nullopt if none.
// front() is copied into `first` before pop_front() removes it; reading
// front() of an empty deque is undefined, hence the check.
std::optional<MemberId> pop() {
if (waiting_.empty()) return std::nullopt;
const MemberId first = waiting_.front();
waiting_.pop_front();
return first;
}
// 1 for the next member to be served; nullopt if not waiting.
// `it - waiting_.begin()` is how many entries come before the match
// (0 for the front); the + 1 turns that into a place counted from 1.
// static_cast converts the signed difference to std::size_t, which is
// safe because it is never negative.
std::optional<std::size_t> position(MemberId member) const {
const auto it = std::find(waiting_.begin(), waiting_.end(), member);
if (it == waiting_.end()) return std::nullopt;
return static_cast<std::size_t>(it - waiting_.begin()) + 1;
}
bool empty() const { return waiting_.empty(); }
std::size_t size() const { return waiting_.size(); }
private:
// A std::deque ("double-ended queue") adds at the back and removes from
// the front cheaply, which is all a queue needs; it can also erase from
// the middle, for a cancel. The front is the member who asked first.
std::deque<MemberId> waiting_;
};

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

title.hpp
// The same plain struct as step 1, with the single optional hold replaced
// by a whole queue. A new title starts with an empty HoldQueue{}.
struct Title {
Isbn isbn;
std::string name;
std::string author;
HoldQueue holds; // step 1 had: std::optional<MemberId> hold;
};

The compiler finds the places to update. The member was renamed from hold to holds on purpose. Building the unchanged step 1 library.cpp against the new Title fails at ten places in five functions: add_title, renew, route, place_hold, and cancel_hold. (Checked with GCC 11.) Had the name stayed hold, some uses might have compiled with a new meaning; a new name for a new meaning makes every old use an error to look at.

Each fix is small. route now serves the queue in order:

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

library.cpp
// Step 2: the same job as in step 1, but the next member now comes from
// the front of the title's queue. The copy must be on the open shelf
// (set_aside throws std::logic_error otherwise); every caller ensures it.
// Changes the caller's local copy and title, which the caller saves.
// Returns who the copy was set aside for, or std::nullopt.
std::optional<MemberId> Library::route(Copy& copy, Title& title, Date today) const {
// pop removes the member who has waited longest and returns them, or
// returns nullopt if nobody waits. Removing them here is what "the
// hold is met" means: they no longer wait in the queue.
const std::optional<MemberId> next = title.holds.pop(); // FR-11: in order
if (!next) return std::nullopt; // stays on the shelf
// *next reads the MemberId out of the optional, known not to be empty.
copy.set_aside(*next, today + days{policy_.hold_days});
return next;
}

And placing a hold lets the queue decide about duplicates:

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

library.cpp
// Step 2: the same checks on the copies as in step 1. What changed is the
// end: instead of "already this member" and "someone else", the queue
// itself refuses a second place for the same member, and any number of
// other members may join behind.
Outcome Library::place_hold(MemberId id, const Isbn& isbn) {
if (!members_.find(id)) return Outcome::unknown_member;
std::optional<Title> title = titles_.find(isbn);
if (!title) return Outcome::unknown_title;
// Refuse if a copy is on the open shelf, or this member already has a
// copy (on loan, or set aside). `if (declaration; condition)` keeps
// each pointer inside its own if; `loan &&` checks it is not nullptr.
for (const Copy& copy : copies_.copies_of(isbn)) {
if (std::holds_alternative<OnShelf>(copy.status())) return Outcome::copy_on_shelf;
if (const auto* loan = std::get_if<OnLoan>(&copy.status()); loan && loan->member == id) {
return Outcome::has_a_copy;
}
if (const auto* held = std::get_if<OnHoldShelf>(&copy.status());
held && held->member == id) {
return Outcome::has_a_copy;
}
}
// add joins the queue at the back, or returns false (and changes
// nothing) if this member is already in it.
if (!title->holds.add(id)) return Outcome::already_held;
titles_.save(*title);
return Outcome::ok;
}
// A member stops waiting. If they are still in the queue, they leave it
// and the others move up. If they have left it because a copy was set
// aside for them, that copy goes back and on to the next in the queue.
Outcome Library::cancel_hold(MemberId id, const Isbn& isbn, Date today) {
std::optional<Title> title = titles_.find(isbn);
if (!title) return Outcome::unknown_title;
// remove returns true only if the member was in the queue.
if (title->holds.remove(id)) {
titles_.save(*title);
return Outcome::ok;
}
// The hold may already have a copy set aside: free it for the next.
// `Copy copy` (not const Copy&): each pass has its own copy to change.
for (Copy copy : copies_.copies_of(isbn)) {
const auto* held = std::get_if<OnHoldShelf>(&copy.status());
if (held != nullptr && held->member == id) {
copy.reshelve(); // back to OnShelf; `held` must not be read now
route(copy, *title, today); // to the front of the queue, if anyone
copies_.save(copy);
titles_.save(*title);
return Outcome::ok;
}
}
return Outcome::no_hold;
}
// The morning job, unchanged from step 1: each copy not collected by its
// last day goes back on the shelf and through route, which now offers it
// to the next member in the queue. Returns the barcodes of the copies it
// moved. The list of copies is taken before the loop, so saving inside the
// loop does not disturb it; `<=` keeps a copy on its last day.
std::vector<Barcode> Library::expire_holds(Date today) {
std::vector<Barcode> moved;
for (Copy copy : copies_.on_hold_shelf()) {
if (today <= std::get<OnHoldShelf>(copy.status()).until) continue;
std::optional<Title> title = titles_.find(copy.isbn());
if (!title) throw std::logic_error("copy refers to a missing title");
copy.reshelve();
route(copy, *title, today);
copies_.save(copy);
titles_.save(*title);
moved.push_back(copy.barcode());
}
return moved;
}
How this code works: What changed in step 2

Three small edits, all in the places that touched Title::hold:

  • route used to read the one waiting member and clear the hold. It now calls holds.pop(), which removes the front member of the queue and returns them, or returns an empty optional if nobody waits.
  • place_hold used to compare the hold with this member, then with anyone. It now calls holds.add(id), which refuses only a member who is already in the queue. hold_taken no longer exists.
  • cancel_hold used to compare the hold with this member. It now calls holds.remove(id), which succeeds only if the member is in the queue, and moves everyone behind them up a place.

The checks on the copies, and the second half of cancel_hold (a copy already set aside), are unchanged.

A trace, from the test ac_6_4_cancelling_with_a_copy_set_aside_passes_it_on:

Call Moss’s queue afterwards M1 afterwards
check_out(ana, M1, 1 March) empty OnLoan{ana, 22 March, 0}
place_hold(ben, moss) Ben unchanged
place_hold(chloe, moss) Ben, Chloe unchanged
check_in(M1, 10 March) Chloe (Ben was popped) OnHoldShelf{ben, 13 March}
cancel_hold(ben, moss, 11 March) empty (Chloe was popped) OnHoldShelf{chloe, 14 March}

In the last call, holds.remove(ben) returns false, because Ben left the queue when the copy was set aside for him. So the loop runs, finds M1 set aside for Ben, puts it back on the shelf, and route pops Chloe and sets M1 aside for her until 11 + 3 = 14 March.

Places in the queue. With Ben and Chloe waiting, position(chloe) finds Chloe one entry after the front: it - waiting_.begin() is 1, and the + 1 makes her place 2.

Outcome::hold_taken can no longer happen, so it was removed. The demo’s switch named it, and stopped compiling until that case was deleted: removing an enumerator is another way to make the compiler find its uses. One function was added, hold_position (FR-10).

What did not move. Copy, CopyStatus, Member, the repository interfaces, the in-memory store, check_out, check_in, and expire_holds are unchanged. check_in and expire_holds gained the queue’s behaviour for free, because they already called route.

The step 1 file is reused for step 2 with three kinds of edit: the Rig reports the queue’s length instead of the single hold, AC-4.2 now expects a second member to be accepted, and the invariant test checks INV-3 against the queue. So the whole step 1 suite runs against step 2. The new tests:

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

test_step2.cpp
// The same Rig as step 1 (S1 and S2 of sail, M1 of moss, all on the
// shelf), except that rig.waiting(isbn) gives the length of the title's
// queue. LLD_TEST, LLD_CHECK, and LLD_CHECK_EQ are as in the step 1 tests.
// A second copy of moss, M2, is added, and Ana borrows both. Chloe asks
// first, then Ben. The first copy back (M2) goes to Chloe, the next (M1)
// to Ben, and the queue is then empty.
LLD_TEST(ac_6_1_members_are_served_in_the_order_they_asked) {
Rig rig;
rig.lib.add_copy(Barcode("M2"), moss, march(1));
rig.lib.check_out(ana, Barcode("M1"), march(1));
rig.lib.check_out(ana, Barcode("M2"), march(1));
rig.lib.place_hold(chloe, moss);
rig.lib.place_hold(ben, moss);
LLD_CHECK(rig.lib.check_in(Barcode("M2"), march(5)).set_aside_for == chloe);
LLD_CHECK(rig.lib.check_in(Barcode("M1"), march(6)).set_aside_for == ben);
LLD_CHECK_EQ(rig.waiting(moss), std::size_t{0});
}
// Ben then Chloe wait. Ben cannot join twice. Ben is 1st, Chloe 2nd, and
// Ana (not waiting) and an unknown ISBN both give an empty optional.
LLD_TEST(ac_6_2_a_member_waits_once_and_can_see_their_place) {
Rig rig;
rig.lib.check_out(ana, Barcode("M1"), march(1));
rig.lib.place_hold(ben, moss);
rig.lib.place_hold(chloe, moss);
LLD_CHECK(rig.lib.place_hold(ben, moss) == Outcome::already_held);
LLD_CHECK(rig.lib.hold_position(ben, moss) == std::optional<std::size_t>{1});
LLD_CHECK(rig.lib.hold_position(chloe, moss) == std::optional<std::size_t>{2});
LLD_CHECK(!rig.lib.hold_position(ana, moss).has_value());
LLD_CHECK(!rig.lib.hold_position(ben, Isbn("9780000000099")).has_value());
}
// M1 is set aside for Ben until 13 March. On the 14th the morning job
// passes it to Chloe, next in the queue, until 17 March; Ben can no
// longer take it.
LLD_TEST(ac_6_3_a_copy_not_collected_goes_to_the_next_member) {
Rig rig;
rig.lib.check_out(ana, Barcode("M1"), march(1));
rig.lib.place_hold(ben, moss);
rig.lib.place_hold(chloe, moss);
rig.lib.check_in(Barcode("M1"), march(10)); // Ben, until 13 March
rig.lib.expire_holds(march(14));
const std::optional<OnHoldShelf> held = rig.as<OnHoldShelf>("M1");
LLD_CHECK(held && held->member == chloe && held->until == march(17));
LLD_CHECK(rig.lib.check_out(ben, Barcode("M1"), march(14)) == Outcome::held_for_another);
}
// M1 is set aside for Ben, who has left the queue. Ben cancels on 11
// March: the copy goes back and on to Chloe, until 11 + 3 = 14 March.
LLD_TEST(ac_6_4_cancelling_with_a_copy_set_aside_passes_it_on) {
Rig rig;
rig.lib.check_out(ana, Barcode("M1"), march(1));
rig.lib.place_hold(ben, moss);
rig.lib.place_hold(chloe, moss);
rig.lib.check_in(Barcode("M1"), march(10)); // Ben
LLD_CHECK(rig.lib.cancel_hold(ben, moss, march(11)) == Outcome::ok);
const std::optional<OnHoldShelf> held = rig.as<OnHoldShelf>("M1");
LLD_CHECK(held && held->member == chloe && held->until == march(14));
}
// Ben leaves the queue before any copy comes back: Chloe moves up to 1st,
// a second cancel by Ben is no_hold, and the returned copy goes to Chloe.
LLD_TEST(ac_6_5_leaving_the_queue_moves_the_others_up) {
Rig rig;
rig.lib.check_out(ana, Barcode("M1"), march(1));
rig.lib.place_hold(ben, moss);
rig.lib.place_hold(chloe, moss);
LLD_CHECK(rig.lib.cancel_hold(ben, moss, march(2)) == Outcome::ok);
LLD_CHECK(rig.lib.hold_position(chloe, moss) == std::optional<std::size_t>{1});
LLD_CHECK(rig.lib.cancel_hold(ben, moss, march(2)) == Outcome::no_hold);
LLD_CHECK(rig.lib.check_in(Barcode("M1"), march(5)).set_aside_for == chloe);
}
// Renewing is refused while the queue has anyone in it (Chloe, after Ben
// leaves), and allowed once the queue is empty.
LLD_TEST(renewing_is_refused_while_anyone_waits_and_allowed_after) {
Rig rig;
rig.lib.check_out(ana, Barcode("M1"), march(1));
rig.lib.place_hold(ben, moss);
rig.lib.place_hold(chloe, moss);
rig.lib.cancel_hold(ben, moss, march(2));
LLD_CHECK(rig.lib.renew(ana, Barcode("M1"), march(3)) == Outcome::holds_waiting);
rig.lib.cancel_hold(chloe, moss, march(3));
LLD_CHECK(rig.lib.renew(ana, Barcode("M1"), march(3)) == Outcome::ok);
}
// The HoldQueue on its own, with no Library: add refuses a duplicate,
// pop serves the front, remove fails for a member no longer in it, and
// pop on an empty queue gives an empty optional instead of failing.
LLD_TEST(the_hold_queue_keeps_its_own_rules) {
HoldQueue queue;
LLD_CHECK(queue.add(ben));
LLD_CHECK(queue.add(chloe));
LLD_CHECK(!queue.add(ben));
LLD_CHECK_EQ(queue.size(), std::size_t{2});
LLD_CHECK(queue.pop() == ben);
LLD_CHECK(!queue.remove(ben));
LLD_CHECK(queue.remove(chloe));
LLD_CHECK(queue.empty());
LLD_CHECK(!queue.pop().has_value());
}
Expected output
-- three members wait
2026-03-02 Ana checks out M1 -> ok
2026-03-03 Ben holds Moss -> ok
2026-03-03 Chloe holds Moss -> ok
2026-03-04 Dev holds Moss -> ok
2026-03-04 Ben holds Moss again -> refused, already waiting
waiting: Ben #1 Chloe #2 Dev #3
2026-03-10 Ana renews M1 -> refused, another member is waiting
-- served in order
2026-03-12 M1 returned -> ok
2026-03-12 M1 set aside for Ben until 2026-03-15
waiting: Chloe #1 Dev #2
2026-03-16 morning job: M1 not collected
2026-03-16 M1 set aside for Chloe until 2026-03-19
2026-03-17 Chloe cancels the hold -> ok
2026-03-17 M1 set aside for Dev until 2026-03-20
2026-03-18 Ben checks out M1 -> refused, set aside for another member
2026-03-18 Dev checks out M1 -> ok
2026-03-18 Ben holds Moss again -> ok
waiting: Ben #1

Ben, Chloe, and Dev queue for the title, A Field Guide to Moss, in that order; Ben’s second hold is refused (AC-6.2), and Ana cannot renew (AC-2.2). When M1 comes back it is set aside for Ben (AC-6.1). Ben does not collect it, so on 16 March it passes to Chloe (AC-6.3). Chloe cancels, and it passes to Dev (AC-6.4). On 18 March Ben cannot take it, because it is set aside for Dev (AC-1.5), and Dev can. Ben’s hold was met on 12 March, so Ben can hold the title again; the queue is now empty, so Ben is #1.

A plan for 45 minutes, using the time boxes from The design workflow:

Time What to do What to say
About 5 min Ask which part of the library, title or copy, loan rules, fines, holds, history, storage. Write FR-1 … FR-9 and the out-of-scope list. “A member waits for a title but walks out with a copy, so those are two classes.”
3–5 min Sketch Title, Copy, Member, the three identifiers, and the copy’s three statuses. Say why there is no Loan class. “With no history kept, a loan is just the status of a copy that is out.”
10–15 min Write CopyStatus, outline Copy and Library, state INV-1 and INV-3. “INV-3 links a title to all its copies, so every path that frees a copy goes through route.”
10–15 min Write check_out and check_in; trace a late return that meets a hold. “Dates are passed in, so the fine is a plain function of its inputs.”
About 5 min Take the queue change, or the database: repositories, one transaction per use case, the lost update. “Two desks can both see the copy on the shelf; the database must refuse the second save.”

What is usually expected at each level

Level Usually expected
Junior Asks about loan rules; separates members from books; writes check out and check in with the loan limit and a fine; uses whole days and integer cents.
Mid-level All of the above, plus: separates titles from copies; holds on titles; makes the copy’s status one value; passes dates in; treats refusals as values; names tests by acceptance criterion.
Senior All of the above, plus: finds the cross-object invariant (INV-3) and one path that keeps it; puts storage behind repositories with aggregate boundaries; raises the lost update and the cross-record loan limit.

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

  • No database adapter. Only the in-memory store exists. The adapter, its transactions, and version checks are the next piece of work.
  • The in-memory store scans. copies_of and on_loan_to look at every copy. That is fine for tests; a database answers with an index.
  • No lost, damaged, or withdrawn copies. A fourth status would be needed, and the fine rules for a lost book.
  • No closed days. A due date can fall on a day the branch is shut.
  • One set of limits. No child, student, or staff categories.
  • The ISBN check digit is not verified. Any thirteen digits pass.
  • No notifications. check_in and expire_holds say who a copy is for; nothing tells the member.
  • No history. As the client asked. Fine disputes cannot be settled from the system.
  • Holds ignore fines and the loan limit. A member who cannot borrow can still place a hold, be served, and then be refused at the desk. The client has not said which they want.
  • Uneven handling of a missing title. check_in throws if a copy’s title is missing, but renew skips the hold check. Both are bugs in the data; one way should be chosen.
  • Policy is not checked. A negative limit would wrap when it is compared with a count.
Requirement Design element Code Tests Status
FR-1 setup add_title, add_copy, add_member step 1 library.cpp setup_mistakes_are_exceptions Tested
FR-2 check out, limits, block check_out, Policy step 1 library.cpp ac_1_1_… to ac_1_6_… Tested
FR-3 renew renew, Copy::renew step 1 library.cpp, copy.cpp ac_2_1_renewing_runs_21_days_from_today_at_most_twice, both ac_2_2_… tests; renewing_is_refused_while_anyone_waits_and_allowed_after (step 2) Tested
FR-4 check in, fines check_in, Member::charge step 1 library.cpp ac_3_1_…, ac_3_2_late_returns_cost_0_25_a_day_up_to_10_00, ac_3_4_… Tested
FR-5 one hold per title Title::hold, place_hold title.hpp, step 1 library.cpp ac_4_1_…, ac_4_2_one_member_waits_per_title Tested
FR-6 a freed copy goes to the holder route step 1 library.cpp ac_3_3_…, ac_4_3_… (both), ac_4_5_… Tested
FR-7 cancel a hold cancel_hold step 1 library.cpp ac_4_4_cancelling_a_hold_frees_it_and_any_copy_set_aside Tested
FR-8 pay pay, Member::pay step 1 library.cpp, member.hpp ac_5_1_paying_reduces_fines_and_bad_amounts_are_refused Tested
FR-9 list loans loans_of step 1 library.cpp ac_1_1_…, ac_3_1_… Tested
FR-5 (changed) a queue HoldQueue step 2 title.hpp, library.cpp ac_6_1_…, ac_6_2_…, the_hold_queue_keeps_its_own_rules (step 2) Tested
FR-10 place in the queue hold_position, HoldQueue::position step 2 library.cpp ac_6_2_…, ac_6_5_… (step 2) Tested
FR-11 passed to the next route with HoldQueue::pop step 2 library.cpp ac_6_3_…, ac_6_4_… (step 2) Tested
NFR-1 storage behind interfaces the three repositories repositories.hpp, memory_store.hpp every test uses the in-memory store; no database adapter exists Partly
NFR-2 dates passed in Date parameters library.hpp every date-dependent test Tested
NFR-3 whole cents Cents types.hpp ac_3_2_…, ac_1_4_… Tested
NFR-4 answers at once small scans in memory memory_store.hpp none Not measured
INV-1 one place per copy CopyStatus copy.hpp by the type; a_copy_refuses_a_change_from_the_wrong_status Reviewed
INV-2 five loans check_out step 1 library.cpp ac_1_3_the_sixth_loan_is_refused (the sixty-day test cannot reach five loans) Tested
INV-3 no waiting title on the shelf place_hold, route step 1 library.cpp inv_2_3_and_5_hold_through_sixty_days, ac_4_1_…, ac_4_5_… Tested
INV-4 a set-aside copy for its member check_out, Copy::lend library.cpp, copy.cpp ac_1_5_…, a_copy_refuses_a_change_from_the_wrong_status Tested
INV-5 fines never negative, capped Member::pay, check_in member.hpp, library.cpp ac_5_1_…, ac_3_2_…, inv_2_3_and_5_hold_through_sixty_days Tested

Exercise: At most five holds per member

The client adds a rule: a member may wait for at most five titles at once.

  1. Where does “how many titles is this member waiting for?” come from? Give two answers, and say what each costs.
  2. Does a copy already set aside for the member count? Who decides?
  3. Write the check in place_hold for your preferred answer.
  4. What would the database version need, given two desks?
Show the explained answer
  1. Ask the titles. Add std::vector<Isbn> held_by(MemberId) const to TitleRepository; in memory it scans every title, and a database answers from an index on the holds. Nothing new to keep in step. Or count on the member. Member gains int holds_, raised by place_hold and lowered when the hold ends. If a set-aside copy counts (item 2), a hold ends not in route but when the copy is collected, expires with no one to take it, or is cancelled, or when a hold that never met a copy is cancelled: four places across check_out, expire_holds, and cancel_hold. route cannot do it anyway, because it is const and never loads a member. Each of those places now changes the member as well as the title or copy, in one transaction. Prefer the query until it is measured to be slow.

  2. It is the client’s call, not the designer’s: ask. Counting it is simpler to explain (“five things waiting for you”), and it is what this sketch assumes.

  3. A sketch, not part of the example:

    IllustrativeA fragment for explanation; not compiled on its own.

    // In Library::place_hold, after the copy loop and the already_held
    // check, so a member at the limit who holds again hears already_held.
    // Count everything this member is waiting for: the titles they hold
    // (held_by is a new TitleRepository query) plus the copies already set
    // aside for them. Every copy on the hold shelf is OnHoldShelf, so
    // std::get<OnHoldShelf> cannot throw here.
    std::size_t waiting = titles_.held_by(id).size();
    for (const Copy& copy : copies_.on_hold_shelf()) {
    if (std::get<OnHoldShelf>(copy.status()).member == id) ++waiting;
    }
    // `>=`: with max_holds 5, a member already waiting for five is refused.
    if (waiting >= static_cast<std::size_t>(policy_.max_holds)) {
    return Outcome::hold_limit; // a new outcome, so the demo's switch must name it
    }

    Policy gains int max_holds = 5;. With step 2’s HoldQueue, held_by is “every title whose holds.position(id) has a value”. Tests: the fifth hold is accepted and the sixth refused; after a cancel, a new hold is accepted; a copy set aside counts.

  4. The same problem as the loan limit under concurrency: two desks each count four and each accept a fifth. The count and the new hold must be in one transaction that locks or versions the member’s record.

  • “Book” is two things. Members wait for a title and walk out with a copy; mixing them makes the commonest questions unanswerable.
  • One answer, “we keep no history”, removed a Loan entity. A loan is the status of a copy that is out.
  • A copy’s status is a std::variant of three small structs, so a copy cannot be in two places, and each status carries only its own data.
  • Links between entities are identifiers, not pointers, which is what storage needs and what sets the aggregate boundaries.
  • The rules read and save through repositories that return copies. A use case that changes several aggregates works on local copies and saves at the end; with a database, that is one transaction.
  • Cross-object rules, like “no waiting title has a copy on the shelf”, need one function that every path goes through.
  • Dates are inputs, so time-dependent rules are plain functions.
  • When a rule changes meaning, change the name too: the compiler then lists every use.