Skip to content

Case study: Parcel locker

Difficulty: Intermediate

Key concepts

  • smallest-fit assignment
  • state machine as a table
  • injected code source
  • injected clock
  • expiry boundary
  • refusal reasons and information leaks
  • roles through access classes
  • concepts as compile-time checks
  • strong exception guarantee
  • size upgrade
  • Observer
  • listener lifetime
  • How to give each parcel the smallest compartment that fits, and why “the first free one” quietly wastes the large compartments.
  • How to write the life of a compartment and of a parcel as two small state machines, each a table of legal moves that the code checks.
  • How a pickup code is drawn from an injected source, made unique, used once, and expired by an injected clock, and what a real locker needs on top (a secure random generator, rate limiting, hashed codes).
  • Where exactly a code stops working: up to, not at, its expiry time, and how a test pins that boundary to the second.
  • Why the bank tells its caller the exact reason a code was refused, but the customer’s screen shows one text for every reason.
  • How to let a courier do courier things and a customer do customer things, checked by the compiler, with two small access classes.
  • How a deposit that builds everything first and changes the bank last leaves nothing half done when something throws.
  • How a change (a larger compartment when a size is full, and listeners told about every change) lands, and an honest verdict on whether the Observer pattern earns its place here.

This page follows the five steps of the delivery framework from How to approach a case study and The delivery framework. It assumes Finding classes, data members, and member functions and State machines and invalid-state prevention.

“We are putting parcel lockers outside our shops. A courier drops parcels in, the customer gets a code and opens the door. Our trial went badly: couriers filled the big doors with envelopes, so large parcels went back to the depot, and a customer worked out that codes went up by one each time. Can you design the software that runs one bank of lockers?”

Two complaints again, and both are about choices the old software made without anyone deciding them. “The first free door” was a choice, and it wasted space. “The next number” was a choice, and it let a stranger open someone else’s door.

Each question is here because its answer changes the design.

Question Answer (from the team) What it changes
What sizes are there? Small, medium, and large. Every bank has its own mix. An enum class Size in order, and a layout passed to the bank when it is built.
Which door does a parcel get? The smallest one it fits. If several are free, any is fine. Its own size only, and the lowest number among those, so the choice is predictable.
What if every door of that size is taken? For now, the courier takes the parcel back. A refusal with a reason. (Using a larger door arrives later as a change.)
How does the customer get in? A six-digit code, sent to their phone. It works once. A code per parcel, from a source the bank does not need to know about.
How long does a code work? 48 hours from the deposit. After that the courier takes the parcel back. An expiry time on each parcel, a clock that can be moved in tests, and a courier collection.
May a code ever be reused for another parcel? No. Support staff must be able to say “that code was used” or “that code expired”. The bank keeps every parcel’s record, and never hands out a code any parcel has had.
What does the screen say when a code is wrong? The same thing whatever went wrong. We had complaints about people testing codes. Exact reasons for the log, one message for the screen.
Who can do what? Couriers deposit and collect. Customers only pick up. Staff can close a broken door. Two roles, kept apart by the type system.
How many people use one bank at once? One screen, one person at a time. Single-threaded, and the page says so.

Three answers decide the shape. “The smallest one it fits” makes assignment a rule the tests can pin. “It works once” and “never reused” make a code part of a parcel’s record, kept after the parcel has gone. “The same thing whatever went wrong” splits what the program knows from what a stranger may learn.

Confirmed:

  • One bank of compartments, each with a number (printed on the door, starting at 1), a size, and a state.
  • Deposit by a courier, into the lowest-numbered free compartment of the parcel’s own size.
  • A pickup code per parcel: unique across every parcel the bank has had, single use, expiring a fixed time after the deposit.
  • Pickup by a customer with the code.
  • Expiry, and collection of expired parcels by a courier.
  • Closing a free compartment, and reopening it.

Assumed (to confirm with the team; see Assumptions):

  • The code is sent to the recipient by something outside the bank. The bank returns it on the receipt; in step 2 a listener sends it.
  • Checking who a courier is (a login, a badge) happens elsewhere.

Out of scope: payments, a network of banks, sending the text message, the door hardware, storing anything on disk, and more than one person at a time. A larger compartment when a size is full, and notifications, arrive as a change in Step 5.

Functional requirements.

  • FR-1 Assignment. A deposited parcel goes into a free compartment of its own size, the lowest-numbered one. If none is free, the deposit is refused, even when a larger compartment is free.
  • FR-2 Codes. Each deposit gets a code no parcel in the bank has ever had. If the source keeps giving used codes, the deposit is refused after three tries.
  • FR-3 Pickup. The right code opens the parcel’s compartment once, and frees it. A wrong, used, or expired code opens nothing.
  • FR-4 Expiry. A code works until its parcel’s expiry time, and not at it. An expired parcel stays inside until a courier collects it.
  • FR-5 Roles. Only a courier deposits, collects, and closes or reopens compartments. Only a customer picks up.
  • FR-6 Compartments. Only a free compartment may be closed, and only a closed one reopened. A closed compartment is never chosen.

Non-functional requirements.

  • NFR-1 No leaks to strangers. The screen shows one message for every refused code. The exact reason goes only to the program.
  • NFR-2 All or nothing. A refused deposit, or one that throws, leaves the bank exactly as it was.
  • NFR-3 Testable without hardware or waiting. The clock and the code source are interfaces, so a test sets the time to the second and knows every code in advance.
  • NFR-4 Not thread-safe, on purpose. One person at one screen.

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

UC-1 Choose a compartment.

  • AC-1.1 A parcel goes into a compartment of its own size.
  • AC-1.2 The lowest-numbered free compartment of that size wins.
  • AC-1.3 With none of its size free, the deposit is refused, even if larger ones are free, and nothing changes; no code is drawn.
  • AC-1.4 A full bank refuses every size.
  • AC-1.5 A closed compartment is never chosen.
  • AC-1.6 A compartment emptied by a pickup is chosen again.

UC-2 Give out a code.

  • AC-2.1 A deposit gets the next code, and expires the hold time after the deposit.
  • AC-2.2 A code any parcel has had (even a picked-up one) is skipped and another drawn.
  • AC-2.3 After three used codes in a row, the deposit is refused and nothing changes.
  • AC-2.4 A code source that throws leaves the bank unchanged.

UC-3 Pick up.

  • AC-3.1 The right code opens the compartment and frees it.
  • AC-3.2 A wrong code is refused and changes nothing.
  • AC-3.3 A code works once.
  • AC-3.4 A code works one second before its expiry time.
  • AC-3.5 At exactly the expiry time it is refused, and the parcel becomes expired but stays inside.
  • AC-3.6 The screen shows one message for every refusal.

UC-4 Courier operations.

  • AC-4.1 Only a courier deposits and collects; only a customer picks up (checked when the tests are compiled).
  • AC-4.2 A courier collects only parcels whose time is up.
  • AC-4.3 Collected parcels are not collected twice, and their codes stay expired.
  • AC-4.4 Expiring marks parcels but leaves them in place.
  • AC-4.5 Only a free compartment goes out of service, and only a closed one returns.

UC-5 The state machines. AC-5.1 and AC-5.2: the compartment and parcel moves are exactly the tables below; AC-5.3 an illegal move throws and changes nothing.

UC-6 Build a bank. AC-6.1 A bank needs at least one compartment and a positive hold time.

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

  • INV-1 A compartment holds a parcel exactly when it is occupied. Kept by Compartment, whose only ways to change state set or clear the parcel in the same call.
  • INV-2 Only legal moves. A compartment and a parcel change state only along their tables. Kept by can_move and the one private function in each class that changes the state.
  • INV-3 No code twice. No two parcels have ever had the same code. Kept by deposit, which checks every record before it accepts a code.
  • INV-4 An open door means a waiting parcel and an unexpired code. Kept by pick_up, the only customer path to release.
  • INV-5 Nothing half done. After any deposit, a parcel record exists exactly when its compartment was occupied. Kept by the order of the steps in deposit.

Step 2 of the framework: Entities and relationships

Section titled “Step 2 of the framework: Entities and relationships”

The nouns from the answers: bank, door, compartment, size, parcel, courier, customer, recipient, code, phone, hours, screen, staff. Filtered:

  • Bank is a LockerBank. Door and compartment are the same thing here: a Compartment, with its Size.
  • Parcel splits in two. What the courier hands over is a ParcelInfo (recipient and size); what the bank keeps is a Parcel record with its code, times, compartment, and state.
  • Code is a string on the record, from a CodeSource. Hours are a hold time and a Clock.
  • Courier and customer are not objects with data; they are roles, and become CourierAccess and CustomerAccess, each offering only its own operations. Staff share the courier’s side in this model.
  • Recipient and phone are one string on ParcelInfo. Screen is whoever calls customer_message.
Entity sketch of step 1. Solid arrows: owns. Dashed arrows: uses or knows without owning
Text description of the diagram

Eight boxes. Dashed arrows from CourierAccess and from CustomerAccess to LockerBank, each labelled knows 1. A solid arrow from LockerBank to Compartment, labelled owns 1 or more, and a solid arrow from LockerBank to Parcel, labelled owns 0 or more, every parcel ever. A solid arrow from Parcel to ParcelInfo, labelled owns 1. A dashed arrow from Compartment to Parcel, labelled knows 0 or 1 by id. Dashed arrows from LockerBank to Clock and to CodeSource, each labelled uses.

Diagram source (Mermaid)
flowchart LR
Courier["CourierAccess"] -.->|"knows 1"| Bank["LockerBank"]
Customer["CustomerAccess"] -.->|"knows 1"| Bank
Bank -->|"owns 1..*"| Compartment
Bank -->|"owns 0..*, every parcel ever"| Parcel
Parcel -->|"owns 1"| ParcelInfo
Compartment -.->|"knows 0..1 by id"| Parcel
Bank -.->|"uses"| Clock
Bank -.->|"uses"| CodeSource

Ownership is the first thing to say out loud. The bank owns its compartments and its parcel records by value, in two vectors. A compartment does not hold a pointer to its parcel, only a ParcelId, so nothing dangles when the vector of records grows. The clock and the code source belong to whoever builds the bank, the composition root, and must outlive it. The two access classes hold a pointer to the bank, so the bank must outlive them too.

Step 3 decides, for each class, what it must remember and what it must do, and justifies each from the requirements. The design below is step 1 of the example, the complete answer to FR-1 to FR-6. The change comes in Step 5.

Requirement What must be remembered Where As
FR-1 sizes, numbers, the lowest free one each compartment’s number, size, and state Compartment number_, size_, state_
FR-3 open the parcel’s compartment which parcel is inside Compartment std::optional<ParcelId> parcel_
FR-2 never reuse a code; support can tell why every code ever given, and its parcel’s state Parcel code_, state_, kept after pickup
FR-4 expiry when the code stops working Parcel TimePoint expires_at_
FR-3 which door to open for a code the parcel’s compartment Parcel CompartmentNumber compartment_
Courier’s input, for the message recipient and size Parcel ParcelInfo info_
FR-1 all compartments; FR-2 all records the compartments, and every parcel ever LockerBank two std::vectors, by value
FR-4 how long a code works the hold time LockerBank std::chrono::seconds hold_time_
NFR-3 time and codes from outside where to ask LockerBank const Clock*, CodeSource*, not owned

Notice what is not stored: no count of free compartments (counted when asked), no “is expired” flag (the state says it), and no map from code to parcel (a search over the records is enough for a sketch, and the code says so).

Need Member function Class
Put a parcel in, take it out, close, reopen (FR-6, INV-1) occupy, release, take_out_of_service, return_to_service Compartment
Is its time up? (FR-4) bool is_overdue(TimePoint now) const Parcel
Move along its table (INV-2) void move_to(ParcelState next) Parcel
A new code (FR-2) std::string next_code() CodeSource
The time (FR-4) TimePoint now() const Clock
Deposit (FR-1, FR-2) DepositResult deposit(const ParcelInfo&), private LockerBank
Pick up (FR-3, FR-4) PickupResult pick_up(std::string_view code), private LockerBank
Expire, and collect what expired (FR-4) expire_overdue(), and private collect_expired() LockerBank
Only a courier’s operations (FR-5) deposit, collect_expired, close and reopen CourierAccess
Only a customer’s operation (FR-5) pick_up CustomerAccess
Words for the screen (NFR-1) customer_message(PickupRefusal) free function

The split follows one question: is this about one thing, or about the rules between things? A compartment knows which moves it may make; it does not know about codes. A parcel knows when its time is up; it does not know which compartments are free. The bank holds the rules that need both: which compartment, which code, which door to open.

A class outline is one box per class, listing its data members (-) and member functions (+) as C++ declarations, as described in Finding classes. Data members are private unless the outline says otherwise.

enum class Size

smallest first; values compare in this order

Values

  • small
  • medium
  • large

struct ParcelId

a strong type around the number; public member

Data members

  • std::size_t value = 0;

struct ParcelInfo

what a courier hands over; public members

Data members

  • std::string recipient;
  • Size size = Size::small;

class Compartment

one door; a value type

Data members

  • CompartmentNumber number_; 1, 2, 3, ... as printed on the door
  • Size size_;
  • CompartmentState state_ = CompartmentState::free;
  • std::optional<ParcelId> parcel_; set exactly when occupied

Member functions

  • void occupy(ParcelId parcel); free to occupied, or throws
  • void release(); occupied to free, or throws
  • void take_out_of_service(); free to out of service, or throws
  • void return_to_service(); out of service to free, or throws

class Parcel

the bank's record, kept after the parcel has gone

Data members

  • ParcelId id_;
  • ParcelInfo info_;
  • CompartmentNumber compartment_;
  • std::string code_;
  • TimePoint deposited_at_;
  • TimePoint expires_at_;
  • ParcelState state_ = ParcelState::deposited;

Member functions

  • bool is_overdue(TimePoint now) const; waiting and now >= expires_at
  • void move_to(ParcelState next); one move from the table, or throws
The value types of step 1

interface (abstract class) Clock

Member functions

  • virtual TimePoint now() const = 0;

interface (abstract class) CodeSource

Member functions

  • virtual std::string next_code() = 0; may throw

class LockerBank

the rules; not copyable; not thread-safe

Data members

  • std::vector<Compartment> compartments_; owned, by value
  • std::vector<Parcel> parcels_; owned; id n is parcels_[n - 1]
  • std::chrono::seconds hold_time_;
  • const Clock* clock_; not owned
  • CodeSource* codes_; not owned

Member functions

  • const std::vector<Compartment>& compartments() const;
  • const Parcel& parcel(ParcelId id) const; throws std::out_of_range
  • std::size_t free_count(Size size) const;
  • std::vector<ParcelId> expire_overdue();
  • DepositResult deposit(const ParcelInfo& info); private, for CourierAccess
  • PickupResult pick_up(std::string_view code); private, for CustomerAccess
  • std::vector<Opened> collect_expired(); private, for CourierAccess

class CourierAccess

the courier's side; the bank must outlive it

Data members

  • LockerBank* bank_;

Member functions

  • DepositResult deposit(const ParcelInfo& info);
  • std::vector<Opened> collect_expired();
  • bool take_out_of_service(CompartmentNumber number);
  • bool return_to_service(CompartmentNumber number);

class CustomerAccess

the customer's side: one operation

Data members

  • LockerBank* bank_;

Member functions

  • PickupResult pick_up(std::string_view code);
The bank, its two access classes, and the two interfaces it uses

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

types.hpp
// The three sizes, smallest first. A parcel of one size fits a compartment
// of that size or any larger one; `enum class` values can be compared with
// < and >, and they compare in the order they are declared here.
enum class Size { small, medium, large };
[[nodiscard]] constexpr std::string_view to_string(Size size) {
switch (size) {
case Size::small: return "small";
case Size::medium: return "medium";
case Size::large: return "large";
}
return "?"; // not reached: every value is handled above
}
// Compartments are numbered 1, 2, 3, ... in the order the bank was built
// with. The number is printed on the door, so it starts at 1, not 0.
using CompartmentNumber = std::size_t;
// A parcel's id. A struct around the number, rather than a bare number,
// so that a parcel id cannot be passed where a compartment number is
// expected by mistake: the compiler refuses it. `= default` on == compares
// the one member.
struct ParcelId {
std::size_t value = 0;
friend bool operator==(ParcelId, ParcelId) = default;
};
// What a courier hands over: who the parcel is for, and how big it is.
struct ParcelInfo {
std::string recipient; // a phone number or account id, used to send the code
Size size = Size::small;
};

Size is an enum class declared smallest first, so Size::small < Size::large is true. Step 1 only compares sizes for equality; step 2’s upgrade rule uses the order. ParcelId is a tiny instance of Strong types: a function that takes a ParcelId cannot be given a compartment number by mistake, although both are a std::size_t underneath. A compartment number is left as a plain alias, because nothing in this design mixes two different kinds of number with it except parcel ids, and those are now a different type.

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

compartment.hpp
// The life of one compartment:
// free -> occupied a courier puts a parcel in
// occupied -> free the customer takes it, or a courier collects it
// free -> out_of_service staff close a broken door
// out_of_service -> free staff reopen it
// Nothing else. In particular an occupied compartment cannot go out of
// service: the parcel inside must come out first, or it would be stuck.
enum class CompartmentState { free, occupied, out_of_service };
[[nodiscard]] constexpr std::string_view to_string(CompartmentState state) {
switch (state) {
case CompartmentState::free: return "free";
case CompartmentState::occupied: return "occupied";
case CompartmentState::out_of_service: return "out of service";
}
return "?";
}
// True if the table above allows a move from `from` to `to`.
[[nodiscard]] constexpr bool can_move(CompartmentState from, CompartmentState to) {
switch (from) {
case CompartmentState::free:
return to == CompartmentState::occupied || to == CompartmentState::out_of_service;
case CompartmentState::occupied:
case CompartmentState::out_of_service:
return to == CompartmentState::free;
}
return false;
}
// One door in the bank: its number, its size, its state, and the parcel
// inside if there is one. A value type: the bank keeps its compartments
// by value in a vector. The rule it keeps (its invariant): it holds a
// parcel id exactly when it is occupied.
class Compartment {
public:
Compartment(CompartmentNumber number, Size size) : number_(number), size_(size) {}
[[nodiscard]] CompartmentNumber number() const { return number_; }
[[nodiscard]] Size size() const { return size_; }
[[nodiscard]] CompartmentState state() const { return state_; }
// The parcel inside, or std::nullopt (no value) when not occupied.
[[nodiscard]] std::optional<ParcelId> parcel() const { return parcel_; }
// Each of these makes one move from the table, and only from the state
// named. Anything else throws std::logic_error and changes nothing. The
// bank checks the state first, so in the bank a throw would be a bug.
void occupy(ParcelId parcel) {
move(CompartmentState::free, CompartmentState::occupied);
parcel_ = parcel;
}
void release() {
move(CompartmentState::occupied, CompartmentState::free);
parcel_.reset(); // empty again
}
void take_out_of_service() { move(CompartmentState::free, CompartmentState::out_of_service); }
void return_to_service() { move(CompartmentState::out_of_service, CompartmentState::free); }
private:
// The one place the state changes. Checking `from` as well as the
// table matters: occupied -> free and out_of_service -> free are both
// legal, but release() must not reopen a closed door.
void move(CompartmentState from, CompartmentState to) {
if (state_ != from || !can_move(from, to)) throw std::logic_error("illegal compartment move");
state_ = to;
}
CompartmentNumber number_;
Size size_;
CompartmentState state_ = CompartmentState::free;
std::optional<ParcelId> parcel_;
};
The states of a compartment, and the moves can_move allows
Text description of the diagram

Three states. Every compartment starts free when the bank is built. From free, occupy goes to occupied when a courier deposits, and take out of service goes to out of service when staff close the door. From occupied, release goes back to free, after a pickup or a courier’s collection. From out of service, return to service goes back to free. There is no arrow between occupied and out of service in either direction.

Diagram source (Mermaid)
stateDiagram-v2
[*] --> free : bank built
free --> occupied : occupy (a courier deposits)
occupied --> free : release (pickup, or a courier collects)
free --> out_of_service : take_out_of_service (staff close the door)
out_of_service --> free : return_to_service (staff reopen it)

The missing arrow is the point. A door with a parcel behind it cannot be closed for repair, or the parcel would be stuck behind a door nobody may open. can_move is the table written as a function, and move checks both the table and the current state. The second check matters because two moves end in free: without it, release() on a closed compartment would pass the table check (out of service to free is legal) and reopen the door by the wrong route.

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

parcel.hpp
// The life of one parcel:
// deposited -> picked_up the customer opened the door with the code
// deposited -> expired the hold time ran out first
// expired -> returned a courier took it out to send it back
// picked_up and returned are final: nothing moves out of them.
enum class ParcelState { deposited, picked_up, expired, returned };
[[nodiscard]] constexpr std::string_view to_string(ParcelState state) {
switch (state) {
case ParcelState::deposited: return "deposited";
case ParcelState::picked_up: return "picked up";
case ParcelState::expired: return "expired";
case ParcelState::returned: return "returned";
}
return "?";
}
// True if the table above allows a move from `from` to `to`.
[[nodiscard]] constexpr bool can_move(ParcelState from, ParcelState to) {
switch (from) {
case ParcelState::deposited:
return to == ParcelState::picked_up || to == ParcelState::expired;
case ParcelState::expired:
return to == ParcelState::returned;
case ParcelState::picked_up:
case ParcelState::returned:
return false;
}
return false;
}
// The bank's record of one parcel, from deposit until long after it has
// gone: the record stays so that a reused code can be told apart from a
// wrong one. A value type, kept by value in the bank's vector.
class Parcel {
public:
Parcel(ParcelId id, ParcelInfo info, CompartmentNumber compartment, std::string code,
TimePoint deposited_at, TimePoint expires_at)
: id_(id),
info_(std::move(info)), // take over the strings instead of copying them again
compartment_(compartment),
code_(std::move(code)),
deposited_at_(deposited_at),
expires_at_(expires_at) {}
[[nodiscard]] ParcelId id() const { return id_; }
[[nodiscard]] const ParcelInfo& info() const { return info_; }
[[nodiscard]] CompartmentNumber compartment() const { return compartment_; }
[[nodiscard]] const std::string& code() const { return code_; }
[[nodiscard]] TimePoint deposited_at() const { return deposited_at_; }
[[nodiscard]] TimePoint expires_at() const { return expires_at_; }
[[nodiscard]] ParcelState state() const { return state_; }
// Still waiting, but its time is up. The boundary counts as expired:
// at exactly expires_at the code no longer works, so "valid for 48
// hours" means valid until one moment before the 48 hours are up.
[[nodiscard]] bool is_overdue(TimePoint now) const {
return state_ == ParcelState::deposited && now >= expires_at_;
}
// Makes one move from the table; an illegal move throws
// std::logic_error and changes nothing.
void move_to(ParcelState next) {
if (!can_move(state_, next)) throw std::logic_error("illegal parcel move");
state_ = next;
}
private:
ParcelId id_;
ParcelInfo info_;
CompartmentNumber compartment_;
std::string code_;
TimePoint deposited_at_;
TimePoint expires_at_;
ParcelState state_ = ParcelState::deposited;
};
The states of a parcel record, and the moves can_move allows
Text description of the diagram

Four states. A record starts in deposited. From deposited, a pickup with the code before the expiry time goes to picked up, and reaching the expiry time goes to expired, noticed either by a pickup attempt or by expire overdue. From expired, a courier’s collection goes to returned. Picked up and returned are final: no move leaves them.

Diagram source (Mermaid)
stateDiagram-v2
[*] --> deposited : deposit
deposited --> picked_up : pick_up with the code, before expires_at
deposited --> expired : now >= expires_at (pick_up or expire_overdue)
expired --> returned : a courier collects it
picked_up --> [*]
returned --> [*]

A record is never deleted, and that is deliberate. The record is what lets the bank say “that code was used” instead of “unknown code”, and what stops the same code being given to a later parcel. The cost is a list that grows forever; a real bank would delete records after some months and keep a separate list of old codes, or simply make codes long enough that a repeat is too unlikely to matter.

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

clock.hpp
// Where the locker bank gets the time: to stamp a deposit and to decide
// whether a pickup code has expired. The tests and the demo pass
// ManualClock and move time by hand, so expiry is checked to the second
// and nothing sleeps.
// TimePoint is a shorter name for "a moment on the wall clock". Adding a
// duration to one (deposit time + hold time) gives another moment.
using TimePoint = std::chrono::system_clock::time_point;
// An interface: its one real function, now(), is `= 0` (pure virtual), so
// a bare Clock cannot be made; a class that derives from it supplies now().
// The bank holds a `const Clock*` and never knows which clock it has.
class Clock {
public:
// Virtual, so destroying a derived clock through a Clock is safe.
virtual ~Clock() = default;
[[nodiscard]] virtual TimePoint now() const = 0;
protected:
// Protected: only derived classes can build or copy a Clock. Code that
// holds two Clock references cannot assign one to the other, which
// would copy only the Clock part of the derived objects (slicing).
Clock() = default;
Clock(const Clock&) = default;
Clock& operator=(const Clock&) = default;
};
// The real time, for a real locker. `final` says nothing derives from it.
class SystemClock final : public Clock {
public:
[[nodiscard]] TimePoint now() const override { return std::chrono::system_clock::now(); }
};
// A clock that stands still until it is told to move: the time is
// whatever it was built with, plus every advance() since.
class ManualClock final : public Clock {
public:
// `explicit` stops a TimePoint from turning into a ManualClock by
// accident, for example when passed to a function.
explicit ManualClock(TimePoint start) : now_(start) {}
[[nodiscard]] TimePoint now() const override { return now_; }
// Throws std::invalid_argument for a negative step.
void advance(std::chrono::seconds step) {
if (step.count() < 0) throw std::invalid_argument("time only moves forward here");
now_ += step;
}
private:
TimePoint now_;
};

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

codes.hpp
// Where pickup codes come from. The bank asks for a code on each deposit
// and does not care how it is made, so the tests and the demo can pass
// ScriptedCodes and know every code in advance.
//
// What a real locker needs instead (none of it is built here):
// - codes from a cryptographically secure random generator (a CSPRNG,
// such as the one the operating system provides). Never std::rand or
// std::mt19937: their next outputs can be worked out from earlier ones.
// - enough digits that guessing is hopeless within the attempt limit.
// - rate limiting: a few wrong codes per screen, then a growing pause, so
// nobody can try codes one after another until one opens a door.
// - storing only a hash of each code, so a copy of the database cannot
// open compartments, and comparing in constant time.
class CodeSource {
public:
virtual ~CodeSource() = default;
// Returns a new code. It may throw; the bank asks before it changes
// anything, so a throw leaves the bank as it was.
[[nodiscard]] virtual std::string next_code() = 0;
protected:
CodeSource() = default;
CodeSource(const CodeSource&) = default;
CodeSource& operator=(const CodeSource&) = default;
};
// Hands out the codes it was given, in order. Once they run out it throws
// std::out_of_range, which the tests use to make the source fail.
class ScriptedCodes final : public CodeSource {
public:
explicit ScriptedCodes(std::vector<std::string> codes) : codes_(std::move(codes)) {}
[[nodiscard]] std::string next_code() override {
if (next_ == codes_.size()) throw std::out_of_range("no scripted codes left");
std::string code = codes_[next_]; // copy first: if the copy throws, next_ is unchanged
++next_;
return code;
}
// How many codes have been handed out so far.
[[nodiscard]] std::size_t used() const { return next_; }
private:
std::vector<std::string> codes_;
std::size_t next_ = 0; // index of the next code to hand out
};

Both are interfaces for the same reason: a test must control them. With ManualClock, a test moves time forward by exactly 48 hours minus one second and checks the code still works. With ScriptedCodes, a test hands over the same code three times and checks the deposit is refused. Neither test could be written against the real clock or a random generator.

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

locker_bank.hpp
// What a deposit gives back. A std::variant holds exactly one of its
// types: a Receipt when the parcel went in, or the reason it did not. So
// a caller cannot read a code from a refused deposit by mistake.
struct Receipt {
ParcelId parcel;
CompartmentNumber compartment = 0;
std::string code; // to be sent to the recipient, not shown to the courier
TimePoint expires_at;
};
enum class DepositRefusal {
no_free_compartment, // every compartment of the parcel's size is taken or closed
no_unique_code, // the code source kept giving codes already used
};
using DepositResult = std::variant<Receipt, DepositRefusal>;
// What a pickup (or a courier's collection) gives back: which door opened.
struct Opened {
ParcelId parcel;
CompartmentNumber compartment = 0;
};
enum class PickupRefusal {
unknown_code, // no parcel ever had this code
code_already_used, // its parcel has been picked up
code_expired, // its parcel's hold time ran out (it may be returned by now)
};
using PickupResult = std::variant<Opened, PickupRefusal>;
[[nodiscard]] std::string_view to_string(DepositRefusal refusal);
[[nodiscard]] std::string_view to_string(PickupRefusal refusal);
// The text for the customer's screen. It is the same for all three
// refusals, on purpose. The exact reason tells a stranger something: "code
// already used" or "code expired" confirms that a code they guessed was
// real. So the bank returns the exact reason to its caller (for the log,
// the tests, and support staff) and the screen shows only this.
[[nodiscard]] std::string_view customer_message(PickupRefusal refusal);

A deposit and a pickup each return a std::variant: the success value, or a refusal reason. A refusal is not an exception, because a full bank or a wrong code is an ordinary outcome that every caller must handle. Exceptions are kept for bugs (an illegal state move) and for failures the bank cannot decide about (a code source that throws, memory running out).

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

locker_bank.hpp
// A bank of compartments, the parcels put in them, and the rules: which
// compartment a parcel gets, its pickup code, and when the code expires.
//
// Ownership: the bank owns its compartments and parcel records, by value.
// It does not own the clock or the code source; whoever builds the bank
// keeps them alive for as long as the bank exists.
//
// Roles: what a courier may do and what a customer may do are private
// here. Only CourierAccess and CustomerAccess (below) can call them, each
// offering just its own role's operations, so the compiler stops code
// that holds only a CustomerAccess from collecting parcels. Anyone with
// the bank can still make a CourierAccess: checking who the courier is (a
// login, a badge) is out of scope.
class LockerBank {
public:
// How many codes to ask for before giving up on a deposit, when the
// source keeps returning codes that some parcel already had.
static constexpr int code_attempts = 3;
// `layout` lists the compartments' sizes; compartment 1 is layout[0].
// `hold_time` is how long a code works after deposit. Throws
// std::invalid_argument for an empty layout or a hold time of zero or less.
LockerBank(const std::vector<Size>& layout, std::chrono::seconds hold_time, const Clock& clock,
CodeSource& codes);
// Not copyable: a copy would be a second bank handing out the same
// codes for the same doors. Deleting copy also means it is not movable,
// which keeps the pointers held by the access objects valid.
LockerBank(const LockerBank&) = delete;
LockerBank& operator=(const LockerBank&) = delete;
// Read-only views for screens, tests, and staff.
[[nodiscard]] const std::vector<Compartment>& compartments() const { return compartments_; }
// Throws std::out_of_range for a number the bank does not have.
[[nodiscard]] const Compartment& compartment(CompartmentNumber number) const;
[[nodiscard]] const Parcel& parcel(ParcelId id) const; // throws std::out_of_range
[[nodiscard]] std::size_t free_count(Size size) const;
// Moves every waiting parcel whose time is up to expired, and returns
// their ids. The parcels stay in their compartments until a courier
// collects them. Neither role's operation: the locker's own timer
// would call this (and collect_expired calls it first).
std::vector<ParcelId> expire_overdue();
private:
friend class CourierAccess; // `friend`: these two classes may use the
friend class CustomerAccess; // private functions below; nothing else can
[[nodiscard]] DepositResult deposit(const ParcelInfo& info);
[[nodiscard]] PickupResult pick_up(std::string_view code);
[[nodiscard]] std::vector<Opened> collect_expired();
[[nodiscard]] bool take_out_of_service(CompartmentNumber number);
[[nodiscard]] bool return_to_service(CompartmentNumber number);
[[nodiscard]] Compartment& slot(CompartmentNumber number);
[[nodiscard]] Parcel& record(ParcelId id);
[[nodiscard]] Compartment* find_free(Size size);
[[nodiscard]] Parcel* find_by_code(std::string_view code);
std::vector<Compartment> compartments_;
std::vector<Parcel> parcels_; // every parcel ever deposited; id n is parcels_[n - 1]
std::chrono::seconds hold_time_;
const Clock* clock_; // not owned
CodeSource* codes_; // not owned
};

The bank is not copyable, and the comment says why: a copy would be a second bank handing out codes for the same doors. Deleting the copy operations also stops the compiler from making move operations, so a bank cannot move to a new address and leave the access objects pointing at the old one.

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

locker_bank.hpp
// The courier's side of the bank. It holds a pointer, not a copy: the bank
// must outlive it.
class CourierAccess {
public:
explicit CourierAccess(LockerBank& bank) : bank_(&bank) {}
[[nodiscard]] DepositResult deposit(const ParcelInfo& info) { return bank_->deposit(info); }
// Opens every compartment holding an expired parcel (expiring any that
// are due first), marks those parcels returned, and frees the
// compartments. Returns what was opened, by compartment number.
[[nodiscard]] std::vector<Opened> collect_expired() { return bank_->collect_expired(); }
// Close or reopen a door. False, and nothing changes, if the
// compartment is not free (to close) or not closed (to reopen).
// Throws std::out_of_range for a number the bank does not have.
// Really a job for maintenance staff; here the courier side stands in
// for every staff role.
[[nodiscard]] bool take_out_of_service(CompartmentNumber number) {
return bank_->take_out_of_service(number);
}
[[nodiscard]] bool return_to_service(CompartmentNumber number) {
return bank_->return_to_service(number);
}
private:
LockerBank* bank_;
};
// The customer's side: one operation, and nothing that opens a door
// without the code.
class CustomerAccess {
public:
explicit CustomerAccess(LockerBank& bank) : bank_(&bank) {}
[[nodiscard]] PickupResult pick_up(std::string_view code) { return bank_->pick_up(code); }
private:
LockerBank* bank_;
};

The courier’s and the customer’s operations are private in LockerBank. Two classes are its friends, so only they can call them, and each passes on only its own role’s operations. CustomerAccess has pick_up and nothing else. Code that holds only a CustomerAccess cannot collect parcels, because there is no function to call: the mistake is a compile error, not a runtime refusal.

That is a design for keeping honest code honest. It does not stop a thief: anyone with the LockerBank can make a CourierAccess. Checking who a courier really is (a login, a badge) is a different job, for the code that decides who gets a CourierAccess, and it is out of scope here.

How does a test check “this does not compile” without failing to compile? With C++20 concepts.

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

test_step1.cpp
// Compile-time role checks: each `requires` asks "would this compile?".
// A private member does not, so the answer is false.
// A concept is a named yes-or-no question about a type T. can_collect<T>
// is true if, for some T object t, the line `t.collect_expired();` would
// compile. Nothing is called: the compiler only checks the expression.
template <typename T>
concept can_collect = requires(T& t) { t.collect_expired(); };
template <typename T>
concept can_deposit = requires(T& t, const ParcelInfo& info) { t.deposit(info); };
template <typename T>
concept can_pick_up = requires(T& t) { t.pick_up("123456"); };

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

test_step1.cpp
LLD_TEST(ac_4_1_only_a_courier_deposits_and_collects_only_a_customer_picks_up) {
LLD_CHECK(can_deposit<CourierAccess> && can_collect<CourierAccess>);
LLD_CHECK(!can_pick_up<CourierAccess>);
LLD_CHECK(can_pick_up<CustomerAccess>);
LLD_CHECK(!can_collect<CustomerAccess> && !can_deposit<CustomerAccess>);
LLD_CHECK(!can_collect<LockerBank> && !can_deposit<LockerBank> && !can_pick_up<LockerBank>);
}
How this code works: Reading the role checks
  1. A concept is a named question about a type, answered true or false by the compiler. can_pick_up<CustomerAccess> asks: “for an object t of type CustomerAccess, would t.pick_up("123456") compile?”
  2. requires(T& t) { ... } is the question’s body. It lists expressions, and the answer is true only if every one of them is valid code. The expressions are never run.
  3. For CustomerAccess, t.pick_up(...) is a public member, so the answer is true. For CourierAccess, there is no pick_up at all, so false. For LockerBank, pick_up exists but is private, and calling it from outside the class is not valid code, so the answer is again false.
  4. The test then checks the answers like any other value. If someone later makes LockerBank::deposit public, can_deposit<LockerBank> becomes true and ac_4_1 fails, which is exactly the warning wanted.

Step 4 writes the important functions, checks their edge cases, and traces a real run by hand. Four things deserve attention: choosing a compartment, drawing a code, making the deposit all or nothing, and picking up.

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

locker_bank.cpp
// The smallest compartment a parcel fits is one of its own size, so step 1
// looks only at that size. Among those it takes the lowest-numbered free
// one, so the choice never depends on anything but the bank's state.
// Returns nullptr (no compartment) when none is free, even if a larger one
// is: step 1 never puts a small parcel in a large compartment.
Compartment* LockerBank::find_free(Size size) {
for (Compartment& c : compartments_) {
if (c.size() == size && c.state() == CompartmentState::free) return &c;
}
return nullptr;
}

The loop walks the compartments in number order and returns the first that is both the parcel’s size and free. Walking in number order is the tie-break: the lowest number wins without any sorting. The test ac_1_2 builds the layout small, medium, small, small and deposits three small parcels; they go to compartments 1, 3, and 4, skipping the medium one.

The pointer it returns points into compartments_. It stays valid for the rest of deposit, because nothing in deposit adds or removes a compartment; only the other vector, parcels_, grows.

A code is drawn only after a compartment has been found, so a refused deposit takes no code (AC-1.3 checks that codes.used() did not move). Each draw is checked against every record, including picked-up and expired ones: that is what makes a code single use for ever, not just while its parcel waits. Three draws are allowed, so a source that returns an old code now and then does not fail a deposit, but a source that is broken does not loop for ever.

A deposit that changes nothing until it cannot fail

Section titled “A deposit that changes nothing until it cannot fail”

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

locker_bank.cpp
// Every step that can fail or throw comes before the first change, so a
// refusal or an exception leaves the bank exactly as it was.
DepositResult LockerBank::deposit(const ParcelInfo& info) {
// 1. Choose the compartment. Nothing has changed yet.
Compartment* chosen = find_free(info.size);
if (chosen == nullptr) return DepositRefusal::no_free_compartment;
// 2. Get a code that no parcel has had. next_code() may throw; if it
// does, the exception leaves here and nothing has changed.
std::string code;
bool unique = false;
for (int attempt = 0; attempt < code_attempts && !unique; ++attempt) {
code = codes_->next_code();
unique = find_by_code(code) == nullptr;
}
if (!unique) return DepositRefusal::no_unique_code;
// 3. Build the record. Copying the strings may throw std::bad_alloc;
// still nothing has changed.
const TimePoint now = clock_->now();
const ParcelId id{parcels_.size() + 1};
Parcel parcel(id, info, chosen->number(), code, now, now + hold_time_);
// 4. Commit. push_back is the last step that can throw (it may need a
// bigger buffer), and if it throws the vector is left unchanged.
// After it, nothing can fail: chosen is free, so occupy() succeeds.
parcels_.push_back(std::move(parcel));
chosen->occupy(id);
return Receipt{id, chosen->number(), std::move(code), now + hold_time_};
}
How this code works: LockerBank::deposit in test ac_2_2

The test builds a bank of two small compartments with the scripted codes 111111, 111111, 111111, 222222. The first deposit gets 111111 and compartment 1, and that parcel is picked up, so compartment 1 is free again and parcel 1’s record is picked up. Then a second deposit:

Step What happens Values Bank changed?
1 find_free(Size::small) compartment 1 (free again, lowest number) no
2a attempt 0: next_code() 111111; parcel 1 had it, so unique is false no
2b attempt 1: next_code() 111111 again; still not unique no
2c attempt 2: next_code() 222222; no record has it, unique is true, the loop stops no
3 build Parcel id 2, compartment 1, code 222222, expires 48 hours after now no
4 parcels_.push_back(std::move(parcel)) the record is now in the bank yes
4 chosen->occupy(id) compartment 1 occupied by parcel 2 yes
5 return Receipt parcel 2, compartment 1, 222222

The test checks the code is 222222 and that four codes were drawn in all. Had the third draw also been used, the loop would end with unique false and the function would return no_unique_code from step 2, with nothing changed (AC-2.3).

Why is this safe when something throws?

  1. Steps 1 to 3 only read the bank. If next_code() throws (the scripted source does when it runs out, AC-2.4), or copying a string throws std::bad_alloc, the exception leaves the function and the bank is as it was.
  2. Step 4 is the commit. push_back is the last thing that can throw (it may need a bigger buffer). If it throws, the standard promises the vector is unchanged, as long as a Parcel can be copied, or moved without throwing. Parcel is both today. The static_assert above the function makes the compiler check the second, so the promise still holds if a later change makes Parcel move-only, and a growing vector moves the records instead of copying them.
  3. After push_back, nothing can fail: chosen was free, so occupy succeeds, and moving the code string into the receipt cannot throw.

This is the strong guarantee from Exception safety: all or nothing.

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

locker_bank.cpp
PickupResult LockerBank::pick_up(std::string_view code) {
Parcel* parcel = find_by_code(code);
if (parcel == nullptr) return PickupRefusal::unknown_code;
switch (parcel->state()) {
case ParcelState::picked_up: return PickupRefusal::code_already_used;
case ParcelState::expired:
case ParcelState::returned: return PickupRefusal::code_expired;
case ParcelState::deposited: break; // still waiting: go on below
}
// Waiting, but its time is up (at expires_at exactly counts): record
// that it expired, and keep the door shut. It stays in the compartment
// for a courier to collect.
if (parcel->is_overdue(clock_->now())) {
parcel->move_to(ParcelState::expired);
return PickupRefusal::code_expired;
}
// The one way a customer opens a door: the parcel is picked up, which
// also makes its code single use, and the compartment is free again.
parcel->move_to(ParcelState::picked_up);
slot(parcel->compartment()).release();
return Opened{parcel->id(), parcel->compartment()};
}
How this code works: LockerBank::pick_up on the four codes of the step 1 demo

The demo deposits at 09:00 on 2 March 2026 (shown as +0h0m) with a hold time of 48 hours, so every code expires at +48h0m.

Time Code entered find_by_code Parcel state Overdue? Result Changed
+2h0m 482913 parcel 1 (alice) deposited no, before +48h Opened, door 1 parcel 1 picked up, compartment 1 free
+2h0m 482913 parcel 1 picked up not asked code_already_used nothing
+2h0m 000000 none none not asked unknown_code nothing
+48h0m 730154 parcel 2 (bob) deposited yes, now >= expires_at code_expired parcel 2 expired; compartment 2 stays occupied

The function asks its questions in order and stops at the first answer: is there such a code, is its parcel still waiting, is its time up. Only if all three pass does a door open. The last row is AC-3.5: the clock is exactly at the expiry time, and that counts as expired. The pickup attempt itself records the expiry, so the next attempt with the same code is refused by the switch, without asking the clock again.

The boundary deserves one more look, because it is where off-by-one mistakes live. The tests pin both sides of it:

Test Deposit Clock at pickup now >= expires_at Result
ac_3_4 2 March 2026, 09:00 4 March 2026, 08:59:59 (48 h − 1 s) false door opens
ac_3_5 2 March 2026, 09:00 4 March 2026, 09:00:00 (48 h) true code_expired

“Valid for 48 hours” is a sentence people read differently; the code picks one meaning, valid up to, not at, writes it in a comment on is_overdue, and two tests hold it there.

pick_up returns one of three reasons, and the program needs them: the log, the tests, and support staff must tell “you typed it wrong” from “your parcel went back to the depot”. The screen must not. A stranger who types random codes and sees “code already used” has learned that the code was real, and that a parcel was delivered to someone recently; “code expired” tells them a parcel may still be inside. So customer_message ignores its argument and returns one text for all three (AC-3.6), and the demo prints both side by side. Keeping the exact reason for the caller and a vague one for the screen is a small instance of not leaking what a stranger should not learn; see Security-sensitive boundaries.

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

locker_bank.cpp
// Only parcels still in a compartment can expire, so this walks the
// compartments (a fixed, small number) rather than every parcel ever.
// It fills the list first, because adding to a vector may throw, and
// changes states only after: an exception leaves no parcel half done.
std::vector<ParcelId> LockerBank::expire_overdue() {
const TimePoint now = clock_->now();
std::vector<ParcelId> due;
for (const Compartment& c : compartments_) {
// `if (init; condition)`: id is the parcel inside, if any.
if (const auto id = c.parcel(); id && parcel(*id).is_overdue(now)) due.push_back(*id);
}
for (const ParcelId id : due) record(id).move_to(ParcelState::expired);
return due;
}
std::vector<Opened> LockerBank::collect_expired() {
static_cast<void>(expire_overdue()); // the list is not needed here, only the effect
std::vector<Opened> opened; // as above: build the list, then change
for (const Compartment& c : compartments_) {
if (const auto id = c.parcel(); id && parcel(*id).state() == ParcelState::expired) {
opened.push_back(Opened{*id, c.number()});
}
}
for (const Opened& o : opened) {
record(o.parcel).move_to(ParcelState::returned);
slot(o.compartment).release();
}
return opened;
}

Both functions follow the deposit’s rule in a smaller form: build the list, then change. Adding to a vector may throw; if it does while the list is being built, no parcel has changed yet. The second loop only changes states, which cannot fail because each move was just checked.

expire_overdue is public and belongs to neither role: a timer in the locker would call it, say once a minute. collect_expired calls it first, so a courier who arrives before the timer has run still collects everything whose time is up (AC-4.2).

Rule Where
Smallest size, lowest number (FR-1) LockerBank::find_free
A code no parcel has had, three tries (FR-2, INV-3) LockerBank::deposit, find_by_code
All or nothing (NFR-2, INV-5) the order of steps in deposit, the static_assert
Once, and not at expiry (FR-3, FR-4) pick_up, Parcel::is_overdue
Legal moves only (INV-1, INV-2) can_move, Compartment::move, Parcel::move_to
One message for the screen (NFR-1) customer_message
Roles (FR-5) private members, CourierAccess, CustomerAccess
Only a free door closes (FR-6) LockerBank::take_out_of_service, and the table

A verification trace follows a run through the code by hand, one step per line, with the state changes after →. Here is the whole step 1 demo, with four compartments: 1 small, 2 small, 3 medium, 4 large. The values are those in the demo’s expected output below.

  1. +0h0m deposit small for alice → compartment 1 occupied, parcel 1, code 482913, expires +48h0m.
  2. +0h0m deposit small for bob → compartment 2 occupied, parcel 2, code 730154.
  3. +0h0m deposit small for carol → refused, no free compartment of that size. The medium compartment 3 is free and is not used. No code is drawn.
  4. +0h0m deposit large for dave → compartment 4 occupied, parcel 3, code 119806 (the third code, because carol’s refusal drew none).
  5. +2h0m alice enters 482913 → compartment 1 opens; parcel 1 picked up; compartment 1 free.
  6. +2h0m alice enters 482913 again → refused, code already used.
  7. +2h0m someone enters 000000 → refused, unknown code.
  8. +48h0m bob enters 730154 → refused, code expired; parcel 2 expired, still in compartment 2. Dave’s parcel is also past its time, but nobody has asked, so it still shows deposited.
  9. courier collects → expire_overdue first moves dave’s parcel to expired; then compartments 2 and 4 open, parcels 2 and 3 returned, both compartments free.
  10. close compartment 1 → done (it was free); compartment 1 out of service.
  11. deposit small for carol → compartment 2 (1 is closed), code 604327, expires +96h0m: 48 hours after the current time, +48h0m.

Step 8 is worth a second look: an expired parcel is not marked until something asks. That is fine because every path that cares (a pickup, a collection) asks first. A screen that listed “parcels waiting” from the states alone would be wrong for a while, which is one reason the locker’s timer calls expire_overdue.

The example has two steps, each a complete program with its own tests and demo:

  • Step 1 is the design above.
  • Step 2 is the change in Step 5: a larger compartment when a size is full, and listeners.

Inside step 1, the small types came first, with the two state tables and their tests (AC-5.x), because everything else relies on them. Then the bank’s assignment, then codes, then pickup and expiry, each tested before the next used it.

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

main.cpp
// CS-16 step 1 demo: deposits, a refusal when a size is full, a pickup,
// a reused code, a wrong code, a code that expires, and a courier
// collecting what was not picked up.
#include <chrono>
#include <iostream>
#include <string>
#include <variant>
#include <vector>
#include "locker_bank.hpp"
using namespace locker;
using namespace std::chrono;
namespace {
const TimePoint start = sys_days{2026y / 3 / 2} + 9h;
// Times are shown as hours and minutes since the demo began.
std::string since_start(TimePoint t) {
const auto passed = duration_cast<minutes>(t - start);
return "+" + std::to_string(passed.count() / 60) + "h" + std::to_string(passed.count() % 60) + "m";
}
// Deposits a parcel and prints what happened. Returns the code, or "" if
// the deposit was refused.
std::string drop_off(CourierAccess& courier, const std::string& recipient, Size size) {
const DepositResult result = courier.deposit(ParcelInfo{recipient, size});
std::cout << "deposit " << to_string(size) << " for " << recipient << ": ";
// std::get_if gives a pointer to the Receipt if that is what the
// variant holds, and nullptr if it holds a refusal.
if (const auto* receipt = std::get_if<Receipt>(&result)) {
std::cout << "compartment " << receipt->compartment << ", code " << receipt->code
<< ", until " << since_start(receipt->expires_at) << '\n';
return receipt->code;
}
std::cout << "refused (" << to_string(std::get<DepositRefusal>(result)) << ")\n";
return "";
}
// Tries a code and prints both what the bank knows and what the screen shows.
void try_code(CustomerAccess& customer, const std::string& who, const std::string& code) {
const PickupResult result = customer.pick_up(code);
std::cout << who << " enters " << code << ": ";
if (const auto* opened = std::get_if<Opened>(&result)) {
std::cout << "compartment " << opened->compartment << " opens\n";
return;
}
const PickupRefusal refusal = std::get<PickupRefusal>(result);
std::cout << "refused, log says \"" << to_string(refusal) << "\", screen says \""
<< customer_message(refusal) << "\"\n";
}
void show(const LockerBank& bank) {
for (const Compartment& c : bank.compartments()) {
std::cout << " " << c.number() << " " << to_string(c.size()) << ": " << to_string(c.state());
if (const auto id = c.parcel()) {
const Parcel& p = bank.parcel(*id);
std::cout << " (" << p.info().recipient << ", " << to_string(p.state()) << ")";
}
std::cout << '\n';
}
}
} // namespace
int main() {
// The clock and code source are made first so they outlive the bank,
// which keeps pointers to them.
ManualClock clock{start};
ScriptedCodes codes{{"482913", "730154", "119806", "604327", "258461"}};
LockerBank bank({Size::small, Size::small, Size::medium, Size::large}, 48h, clock, codes);
CourierAccess courier{bank};
CustomerAccess customer{bank};
const std::string alice = drop_off(courier, "alice", Size::small);
const std::string bob = drop_off(courier, "bob", Size::small);
drop_off(courier, "carol", Size::small); // both small ones are taken
drop_off(courier, "dave", Size::large);
show(bank);
clock.advance(2h);
try_code(customer, "alice", alice);
try_code(customer, "alice", alice); // the same code a second time
try_code(customer, "someone", "000000");
clock.advance(46h); // now exactly 48 hours after bob's deposit
try_code(customer, "bob", bob);
show(bank);
const std::vector<Opened> collected = courier.collect_expired();
std::cout << "courier collects:";
for (const Opened& o : collected) std::cout << " compartment " << o.compartment;
std::cout << '\n';
std::cout << "close compartment 1: " << (courier.take_out_of_service(1) ? "done" : "refused") << '\n';
drop_off(courier, "carol", Size::small);
show(bank);
}
Expected output
deposit small for alice: compartment 1, code 482913, until +48h0m
deposit small for bob: compartment 2, code 730154, until +48h0m
deposit small for carol: refused (no free compartment of that size)
deposit large for dave: compartment 4, code 119806, until +48h0m
1 small: occupied (alice, deposited)
2 small: occupied (bob, deposited)
3 medium: free
4 large: occupied (dave, deposited)
alice enters 482913: compartment 1 opens
alice enters 482913: refused, log says "code already used", screen says "This code cannot be used. Check it, or contact customer service."
someone enters 000000: refused, log says "unknown code", screen says "This code cannot be used. Check it, or contact customer service."
bob enters 730154: refused, log says "code expired", screen says "This code cannot be used. Check it, or contact customer service."
1 small: free
2 small: occupied (bob, expired)
3 medium: free
4 large: occupied (dave, deposited)
courier collects: compartment 2 compartment 4
close compartment 1: done
deposit small for carol: compartment 2, code 604327, until +96h0m
1 small: out of service
2 small: occupied (carol, deposited)
3 medium: free
4 large: free

Each line matches a step of the trace above. Note the order in main: the clock and the code source are made before the bank, and the access objects after it. Objects in a function are destroyed in reverse order, so the bank goes before the clock and codes it points at, and the access objects go before the bank.

The 25 step 1 tests are named after the acceptance criteria. Every test builds a World, whose member order does the same job as the order in main:

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

test_step1.cpp
// Everything a test needs. The members are built in the order written and
// destroyed in reverse, so the clock and codes outlive the bank that
// points at them.
struct World {
ManualClock clock{start};
ScriptedCodes codes;
LockerBank bank;
CourierAccess courier{bank};
CustomerAccess customer{bank};
explicit World(const std::vector<Size>& layout = {Size::small, Size::small, Size::medium, Size::large},
std::vector<std::string> code_list = numbered_codes(50))
: codes(std::move(code_list)), bank(layout, hold, clock, codes) {}
// Deposits and returns the receipt; the test fails if it was refused.
Receipt put(Size size, const std::string& recipient = "alice") {
DepositResult result = courier.deposit(ParcelInfo{recipient, size});
LLD_CHECK(std::holds_alternative<Receipt>(result));
if (auto* receipt = std::get_if<Receipt>(&result)) return *receipt;
return Receipt{};
}
};

The assignment tests pin the rule exactly, including the refusal that the change will alter:

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

test_step1.cpp
LLD_TEST(ac_1_1_a_parcel_goes_in_a_compartment_of_its_own_size) {
World w({Size::large, Size::medium, Size::small}); // the small one is last
LLD_CHECK_EQ(w.put(Size::small).compartment, CompartmentNumber{3});
LLD_CHECK_EQ(w.put(Size::medium).compartment, CompartmentNumber{2});
LLD_CHECK_EQ(w.put(Size::large).compartment, CompartmentNumber{1});
}
LLD_TEST(ac_1_2_the_lowest_numbered_free_compartment_of_that_size_wins) {
World w({Size::small, Size::medium, Size::small, Size::small});
LLD_CHECK_EQ(w.put(Size::small).compartment, CompartmentNumber{1});
LLD_CHECK_EQ(w.put(Size::small).compartment, CompartmentNumber{3});
LLD_CHECK_EQ(w.put(Size::small).compartment, CompartmentNumber{4});
}
LLD_TEST(ac_1_3_no_free_compartment_of_the_size_refuses_even_if_larger_ones_are_free) {
World w; // small, small, medium, large
static_cast<void>(w.put(Size::small));
static_cast<void>(w.put(Size::small));
const auto before = states(w.bank);
LLD_CHECK_EQ(refusal_of(w.courier.deposit({"bob", Size::small})), DepositRefusal::no_free_compartment);
LLD_CHECK(states(w.bank) == before);
LLD_CHECK_EQ(w.codes.used(), std::size_t{2}); // a refused deposit takes no code
LLD_CHECK_EQ(w.bank.free_count(Size::large), std::size_t{1});
}
LLD_TEST(ac_1_4_a_full_bank_refuses_every_size) {
World w;
static_cast<void>(w.put(Size::small));
static_cast<void>(w.put(Size::small));
static_cast<void>(w.put(Size::medium));
static_cast<void>(w.put(Size::large));
for (const Size size : {Size::small, Size::medium, Size::large}) {
LLD_CHECK_EQ(refusal_of(w.courier.deposit({"bob", size})), DepositRefusal::no_free_compartment);
}
LLD_CHECK_EQ(w.codes.used(), std::size_t{4});
}
LLD_TEST(ac_1_5_a_compartment_out_of_service_is_never_chosen) {
World w;
LLD_CHECK(w.courier.take_out_of_service(1));
LLD_CHECK_EQ(w.put(Size::small).compartment, CompartmentNumber{2});
LLD_CHECK_EQ(refusal_of(w.courier.deposit({"bob", Size::small})), DepositRefusal::no_free_compartment);
}
LLD_TEST(ac_1_6_a_compartment_emptied_by_pickup_is_chosen_again) {
World w({Size::small});
const Receipt first = w.put(Size::small);
static_cast<void>(w.customer.pick_up(first.code));
const Receipt second = w.put(Size::small, "bob");
LLD_CHECK_EQ(second.compartment, CompartmentNumber{1});
LLD_CHECK(!(second.parcel == first.parcel));
LLD_CHECK(w.bank.compartment(1).parcel() == second.parcel);
}

The pickup tests pin the boundary and the single message:

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

test_step1.cpp
LLD_TEST(ac_3_1_the_right_code_opens_the_compartment_and_frees_it) {
World w;
const Receipt receipt = w.put(Size::small);
const PickupResult result = w.customer.pick_up(receipt.code);
const auto* opened = std::get_if<Opened>(&result);
LLD_CHECK(opened != nullptr);
if (opened != nullptr) {
LLD_CHECK_EQ(opened->compartment, receipt.compartment);
LLD_CHECK_EQ(opened->parcel, receipt.parcel);
}
LLD_CHECK_EQ(w.bank.parcel(receipt.parcel).state(), ParcelState::picked_up);
LLD_CHECK_EQ(w.bank.compartment(receipt.compartment).state(), CompartmentState::free);
LLD_CHECK(!w.bank.compartment(receipt.compartment).parcel().has_value());
}
LLD_TEST(ac_3_2_a_wrong_code_is_refused_and_changes_nothing) {
World w;
const Receipt receipt = w.put(Size::small);
LLD_CHECK_EQ(refusal_of(w.customer.pick_up("999999")), PickupRefusal::unknown_code);
LLD_CHECK_EQ(refusal_of(w.customer.pick_up("")), PickupRefusal::unknown_code);
LLD_CHECK_EQ(w.bank.parcel(receipt.parcel).state(), ParcelState::deposited);
LLD_CHECK_EQ(w.bank.compartment(receipt.compartment).state(), CompartmentState::occupied);
}
LLD_TEST(ac_3_3_a_code_works_once) {
World w;
const Receipt receipt = w.put(Size::small);
LLD_CHECK(std::holds_alternative<Opened>(w.customer.pick_up(receipt.code)));
const Receipt next = w.put(Size::small, "bob"); // takes compartment 1 again
LLD_CHECK_EQ(next.compartment, receipt.compartment);
LLD_CHECK_EQ(refusal_of(w.customer.pick_up(receipt.code)), PickupRefusal::code_already_used);
LLD_CHECK_EQ(w.bank.parcel(next.parcel).state(), ParcelState::deposited); // bob's is safe
}
LLD_TEST(ac_3_4_a_code_works_until_one_second_before_expiry) {
World w;
const Receipt receipt = w.put(Size::small);
w.clock.advance(hold - 1s);
LLD_CHECK(std::holds_alternative<Opened>(w.customer.pick_up(receipt.code)));
}
LLD_TEST(ac_3_5_at_exactly_the_expiry_time_the_code_is_refused_and_the_parcel_expires) {
World w;
const Receipt receipt = w.put(Size::small);
w.clock.advance(hold);
LLD_CHECK_EQ(refusal_of(w.customer.pick_up(receipt.code)), PickupRefusal::code_expired);
LLD_CHECK_EQ(w.bank.parcel(receipt.parcel).state(), ParcelState::expired);
// The parcel is still inside, waiting for a courier.
LLD_CHECK_EQ(w.bank.compartment(receipt.compartment).state(), CompartmentState::occupied);
LLD_CHECK_EQ(refusal_of(w.customer.pick_up(receipt.code)), PickupRefusal::code_expired);
}
LLD_TEST(ac_3_6_the_screen_shows_one_message_for_every_refusal) {
const std::string_view text = customer_message(PickupRefusal::unknown_code);
LLD_CHECK(customer_message(PickupRefusal::code_already_used) == text);
LLD_CHECK(customer_message(PickupRefusal::code_expired) == text);
LLD_CHECK(to_string(PickupRefusal::unknown_code) != to_string(PickupRefusal::code_expired));
}

The courier tests check that collection takes only what is due, and that expiring and collecting are separate:

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

test_step1.cpp
LLD_TEST(ac_4_2_a_courier_collects_only_parcels_whose_time_is_up) {
World w;
const Receipt early = w.put(Size::small, "alice");
w.clock.advance(1h);
const Receipt late = w.put(Size::large, "bob");
const Receipt taken = w.put(Size::medium, "carol");
static_cast<void>(w.customer.pick_up(taken.code));
w.clock.advance(hold - 1h); // alice's time is up exactly now; bob's in an hour
const std::vector<Opened> opened = w.courier.collect_expired();
LLD_CHECK_EQ(opened.size(), std::size_t{1});
if (!opened.empty()) {
LLD_CHECK_EQ(opened[0].parcel, early.parcel);
LLD_CHECK_EQ(opened[0].compartment, early.compartment);
}
LLD_CHECK_EQ(w.bank.parcel(early.parcel).state(), ParcelState::returned);
LLD_CHECK_EQ(w.bank.compartment(early.compartment).state(), CompartmentState::free);
LLD_CHECK_EQ(w.bank.parcel(late.parcel).state(), ParcelState::deposited);
LLD_CHECK_EQ(w.bank.parcel(taken.parcel).state(), ParcelState::picked_up);
}
LLD_TEST(ac_4_3_collected_parcels_are_not_collected_twice_and_their_codes_stay_expired) {
World w;
const Receipt a = w.put(Size::small, "alice");
const Receipt b = w.put(Size::large, "bob");
w.clock.advance(hold);
LLD_CHECK_EQ(refusal_of(w.customer.pick_up(a.code)), PickupRefusal::code_expired); // a expires here
const std::vector<Opened> opened = w.courier.collect_expired(); // b expires here
LLD_CHECK_EQ(opened.size(), std::size_t{2});
if (opened.size() == 2) { // in compartment order
LLD_CHECK_EQ(opened[0].parcel, a.parcel);
LLD_CHECK_EQ(opened[1].parcel, b.parcel);
}
LLD_CHECK(w.courier.collect_expired().empty());
LLD_CHECK_EQ(refusal_of(w.customer.pick_up(b.code)), PickupRefusal::code_expired);
LLD_CHECK_EQ(w.bank.parcel(b.parcel).state(), ParcelState::returned);
}
LLD_TEST(ac_4_4_expiring_marks_parcels_but_leaves_them_in_place) {
World w;
const Receipt a = w.put(Size::small);
w.clock.advance(hold - 1s);
LLD_CHECK(w.bank.expire_overdue().empty());
w.clock.advance(1s);
const std::vector<ParcelId> due = w.bank.expire_overdue();
LLD_CHECK_EQ(due.size(), std::size_t{1});
LLD_CHECK_EQ(w.bank.parcel(a.parcel).state(), ParcelState::expired);
LLD_CHECK_EQ(w.bank.compartment(a.compartment).state(), CompartmentState::occupied);
LLD_CHECK(w.bank.expire_overdue().empty()); // already expired: not listed again
}

The other tests check each state table against every pair of states (AC-5.1, AC-5.2), that an illegal move throws and changes nothing (AC-5.3), that only a free compartment closes (AC-4.5), and that a bank needs compartments and a positive hold time (AC-6.1).

Step 5 asks what happens when the requirements change, and whether the design bends or breaks.

“Couriers hate taking parcels back when the small doors are full and a medium one is empty. Put the parcel in the next size up. Also, we want the code sent by text message as soon as a parcel goes in, a log for our staff, and a status screen in the shop, all told when a parcel goes in, comes out, or expires.”

Two changes. The first changes one rule. The second adds things that want to hear about changes without the bank knowing what they do with the news.

UC-7 Size upgrade. AC-1.3 now reads “no free compartment of the parcel’s size or larger”, and:

  • AC-7.1 A free compartment of the parcel’s own size is used first.
  • AC-7.2 When its size is full, a parcel goes up one size, not straight to the largest.
  • AC-7.3 When the next size is full too, it goes up again.
  • AC-7.4 The cost: an upgraded parcel can crowd out a larger one.
  • AC-7.5 Upgrading skips closed compartments, and an exact fit is not an upgrade. The receipt says whether the parcel was upgraded.

UC-8 Notifications.

  • AC-8.1 Every listener hears every event, in the order the listeners were added.
  • AC-8.2 Events carry the facts of the change (parcel, compartment, recipient, and for a deposit the code, expiry, and upgrade flag).
  • AC-8.3 Listeners are called after the change is complete.
  • AC-8.4 A listener that throws changes nothing for the others or for the result.
  • AC-8.5 A removed listener hears nothing, and the list has no duplicates.
  • AC-8.6 Changing the listener list from inside a listener is refused.
  • AC-8.7 Refused and failed operations send no event.
  • AC-8.8 A parcel expires once, and its event is sent once.
  • AC-8.9 A listener that calls back into the bank starts a second round of events inside the first. The loop survives, and the list stays locked until the outer round ends; listeners later in the list hear the inner event first (see the warning below).
File Change
types.hpp all_sizes, every size smallest first, for the upgrade loop
locker_bank.cpp find_free tries each size from the parcel’s own upwards; the refusal text says “or larger”
locker_bank.hpp Receipt::upgraded; listener functions; notify; three new data members
events.hpp new: the three events and the LockerListener interface
locker_bank.cpp add_listener, remove_listener; deposit, pick_up, and expire_overdue build an event and send it after the change
everything else unchanged: Compartment, Parcel, Clock, CodeSource, and both access classes

The state machines did not change at all, nor did the roles. That is the sign of a split that held: the change was about which compartment and about who hears, and those lived in one place each.

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

locker_bank.cpp
// The upgrade rule (the step 2 change): try the parcel's own size first;
// if none of that size is free, try the next larger size, then the next.
// The first size with a free compartment wins, and within it the
// lowest-numbered one. A parcel never goes in a smaller compartment.
// Returns nullptr when no compartment of the parcel's size or larger is free.
//
// The cost: a small parcel in a large compartment takes the space a large
// parcel needed. A large parcel that arrives later may be refused, even
// if the small compartments have emptied since. The rule trades that
// risk for not turning a small parcel away now. A bank that sees many
// large parcels might keep the last large compartment for large parcels
// only.
Compartment* LockerBank::find_free(Size size) {
for (const Size candidate : all_sizes) {
if (candidate < size) continue; // too small for this parcel
for (Compartment& c : compartments_) {
if (c.size() == candidate && c.state() == CompartmentState::free) return &c;
}
}
return nullptr;
}
How this code works: find_free in the step 2 demo

The bank is 1 small, 2 small, 3 medium, 4 large. Alice and bob have taken compartments 1 and 2.

Deposit Candidate size Free compartments of that size Result upgraded
carol, small small none (1 and 2 taken) try the next size
medium 3 compartment 3 true
dave, small small none try the next size
medium none (3 taken) try the next size
large 4 compartment 4 true
erin, large small, medium skipped: smaller than large
large none (4 taken by dave) no_free_compartment

The outer loop goes through the sizes smallest first and skips any smaller than the parcel. The inner loop is step 1’s loop for one size. The first size with a free compartment wins, so a parcel goes up one size at a time, never straight to the largest. deposit sets upgraded when the chosen compartment’s size is not the parcel’s.

The last row is the cost, and the demo shows it on purpose. Dave’s envelope sits in the only large compartment, and erin’s large parcel goes back to the depot. The new rule trades a sure refusal now (dave) for a possible refusal later (erin). Whether that is a good trade depends on how many large parcels arrive, which is a question for the team, not for the code. The receipt’s upgraded flag, and the audit log’s “(larger than needed)”, make the cost visible so that someone can measure it.

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

events.hpp
// What the bank tells its listeners. Each event is a plain value with
// copies of the facts, not a reference into the bank, so a listener may
// keep it as long as it likes.
struct Deposited {
ParcelId parcel;
CompartmentNumber compartment = 0;
std::string recipient;
std::string code; // for the message to the recipient; a log should not keep it
TimePoint expires_at;
bool upgraded = false; // put in a larger compartment than its size
};
struct PickedUp {
ParcelId parcel;
CompartmentNumber compartment = 0;
std::string recipient;
TimePoint at;
};
struct Expired {
ParcelId parcel;
CompartmentNumber compartment = 0;
std::string recipient;
TimePoint at; // when the bank noticed, which may be after expires_at
};
// Observer: anything that wants to hear about deposits, pickups, and
// expiries derives from this and overrides the functions it cares about;
// the others do nothing.
//
// The bank calls a listener only after the change is complete, so a
// listener that asks the bank sees the new state. A listener that throws
// does not undo the change or stop the other listeners: the bank catches
// the exception and counts it (see LockerBank::listener_failures).
class LockerListener {
public:
virtual ~LockerListener() = default;
virtual void on_deposited(const Deposited&) {} // no parameter name: unused here
virtual void on_picked_up(const PickedUp&) {}
virtual void on_expired(const Expired&) {}
protected:
LockerListener() = default;
LockerListener(const LockerListener&) = default;
LockerListener& operator=(const LockerListener&) = default;
};

Each event is a plain value holding copies of the facts. A listener may keep it as long as it likes, and nothing it holds points into the bank. LockerListener is the Observer pattern’s interface, as in Observer: three virtual functions, each with an empty default, so a listener overrides only the events it cares about.

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

locker_bank.hpp
// Listeners, called in the order they were added. The bank keeps a
// plain pointer and does not own the listener: whoever adds one keeps
// it alive, and removes it before destroying it (or destroys the bank
// first). Adding one already added, or removing one not added, returns
// false and changes nothing. Both throw std::logic_error if called from
// inside a listener while events are being sent, because changing the
// list while the bank walks through it would break the walk.
bool add_listener(LockerListener& listener);
bool remove_listener(LockerListener& listener);
// How many times a listener has thrown. The bank cannot know what a
// failed listener meant to do, so it counts; a real bank would log it.
[[nodiscard]] std::size_t listener_failures() const { return listener_failures_; }

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

locker_bank.hpp
// Sends one event to every listener. `tell` is a function (usually a
// lambda) that calls the right on_... function on the listener it is
// given. Every exception is caught here, so this cannot throw, and
// `noexcept` promises that; an operation that has already changed the
// bank can then return normally. The depth counter, not a true/false
// flag, copes with a listener that calls back into the bank and so
// starts a second round of events inside the first.
template <typename Tell>
void notify(const Tell& tell) noexcept {
++notify_depth_;
for (LockerListener* listener : listeners_) {
try {
tell(*listener);
} catch (...) { // `...` catches anything, not only std::exception
++listener_failures_;
}
}
--notify_depth_;
}
How this code works: notify, and who must outlive whom
  1. notify takes tell, a small function that knows which on_... to call. Each caller passes a lambda such as [&event](LockerListener& listener) { listener.on_deposited(event); }: it captures the event by reference (the event lives until notify returns) and calls one function on whichever listener it is given. notify is a template so that each lambda is used directly, without wrapping it in a std::function.
  2. The loop calls the listeners in the order they were added (AC-8.1). Each call is inside its own try, so one listener that throws does not stop the next one, and catch (...) catches anything, even an exception that is not a std::exception. The failure is counted.
  3. Because every exception is caught, notify cannot throw, and noexcept says so. That matters: notify runs after the bank has changed, so an exception escaping from it would tell the caller “this failed” about a deposit that has in fact happened (AC-8.4).
  4. notify_depth_ counts how many rounds of notify are running. While it is above 0, add_listener and remove_listener throw std::logic_error. Changing listeners_ while the loop walks it could move or free the vector’s buffer under the loop. The throw happens inside a listener, so notify catches and counts it too (AC-8.6).
  5. Lifetimes. The bank keeps a plain pointer to each listener and does not own it. So a listener must stay alive for as long as it is on the list. Two ways keep that true: remove the listener before destroying it, or destroy the bank first. The step 2 demo does the second, by declaring the listeners before the bank: objects in a function are destroyed in reverse order, so the bank goes first.

In the step 2 demo, the listeners are texts, log, and screen, in that order. When alice picks up parcel 1, texts has no on_picked_up and does nothing, log prints [log] parcel 1 picked up from 1, and screen throws screen offline. notify catches it, listener_failures() becomes 1, and pick_up still returns Opened; the demo prints listener failures: 1.

The step 2 deposit builds its event with the record, before the change, because copying the strings may throw, and sends it after:

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

locker_bank.cpp
// Every step that can fail or throw comes before the first change, so a
// refusal or an exception leaves the bank exactly as it was. The event is
// built before the change too (it copies strings, which may throw), and
// sent after it, when the bank is in its new state.
DepositResult LockerBank::deposit(const ParcelInfo& info) {
// 1. Choose the compartment. Nothing has changed yet.
Compartment* chosen = find_free(info.size);
if (chosen == nullptr) return DepositRefusal::no_free_compartment;
// 2. Get a code that no parcel has had. next_code() may throw; if it
// does, the exception leaves here and nothing has changed.
std::string code;
bool unique = false;
for (int attempt = 0; attempt < code_attempts && !unique; ++attempt) {
code = codes_->next_code();
unique = find_by_code(code) == nullptr;
}
if (!unique) return DepositRefusal::no_unique_code;
// 3. Build the record and the event. Copying the strings may throw
// std::bad_alloc; still nothing has changed.
const TimePoint now = clock_->now();
const ParcelId id{parcels_.size() + 1};
const bool upgraded = chosen->size() != info.size;
Parcel parcel(id, info, chosen->number(), code, now, now + hold_time_);
const Deposited event{id, chosen->number(), info.recipient, code, now + hold_time_, upgraded};
// 4. Commit. push_back is the last step that can throw (it may need a
// bigger buffer), and if it throws the vector is left unchanged.
// After it, nothing can fail: chosen is free, so occupy() succeeds.
parcels_.push_back(std::move(parcel));
chosen->occupy(id);
// 5. Tell the listeners. notify() cannot throw.
notify([&event](LockerListener& listener) { listener.on_deposited(event); });
return Receipt{id, chosen->number(), std::move(code), now + hold_time_, upgraded};
}
A deposit in the step 2 demo, with its three listeners
Text description of the diagram

Seven participants: CourierAccess, LockerBank, CodeSource, Clock, TextMessages, AuditLog, and BrokenScreen. CourierAccess asks LockerBank to deposit carol’s small parcel. LockerBank finds compartment 3, a medium one, asks the CodeSource for a code and gets 119806, and asks the Clock for the time. It builds the Parcel record and the Deposited event, marked upgraded, then adds the record and occupies compartment 3. Only then does it call on_deposited on TextMessages, which sends the text with the code, on AuditLog, which logs parcel 3 in 3, larger than needed, and on BrokenScreen, which does nothing for a deposit. Last, LockerBank returns the receipt to CourierAccess: compartment 3, code 119806, upgraded.

Diagram source (Mermaid)
sequenceDiagram
participant C as CourierAccess
participant B as LockerBank
participant S as CodeSource
participant K as Clock
participant T as TextMessages
participant L as AuditLog
participant X as BrokenScreen
C->>B: deposit(carol, small)
B->>B: find_free(small): compartment 3, medium
B->>S: next_code()
S-->>B: "119806"
B->>K: now()
K-->>B: +0h0m
B->>B: build Parcel and Deposited event (upgraded)
B->>B: push_back record, occupy compartment 3
B->>T: on_deposited(event)
T-->>B: sends the text with the code
B->>L: on_deposited(event)
L-->>B: logs "parcel 3 in 3 (larger than needed)"
B->>X: on_deposited(event)
X-->>B: does nothing (default)
B-->>C: Receipt (3, "119806", upgraded)

An honest verdict. If the only thing that ever wanted news were the text message sender, a single std::function<void(const Deposited&)> passed to the bank would be simpler: one callback, no interface, no list, no rules about changing the list. Do not reach for Observer for one listener.

Here the request names three independent listeners (texts, the staff log, the shop screen), each caring about different events, added by different parts of the program, and more are likely. A list of listeners with one interface fits that. The cost is real and visible in the code: a lifetime rule, a rule about changing the list while it is used, and exception handling around every call. That is the usual price of Observer, as the Observer page explains.

struct Deposited

public members; copies, not references

Data members

  • ParcelId parcel;
  • CompartmentNumber compartment = 0;
  • std::string recipient;
  • std::string code;
  • TimePoint expires_at;
  • bool upgraded = false;

struct PickedUp

public members

Data members

  • ParcelId parcel;
  • CompartmentNumber compartment = 0;
  • std::string recipient;
  • TimePoint at;

struct Expired

public members; at is when the bank noticed

Data members

  • ParcelId parcel;
  • CompartmentNumber compartment = 0;
  • std::string recipient;
  • TimePoint at;

interface (abstract class) LockerListener

each function has an empty default

Member functions

  • virtual void on_deposited(const Deposited&);
  • virtual void on_picked_up(const PickedUp&);
  • virtual void on_expired(const Expired&);

class LockerBank

only the additions

Data members

  • std::vector<LockerListener*> listeners_; not owned
  • std::size_t listener_failures_ = 0;
  • int notify_depth_ = 0; above 0 while events are being sent

Member functions

  • bool add_listener(LockerListener& listener); false if already there
  • bool remove_listener(LockerListener& listener); false if not there
  • std::size_t listener_failures() const;
  • void notify(const Tell& tell) noexcept; private template
What step 2 adds; everything else is as in step 1

The 39 step 2 tests are the 25 of step 1 (with AC-1.3 and AC-1.5 changed by the upgrade rule) and 14 new ones. The upgrade tests:

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

test_step2.cpp
LLD_TEST(ac_7_1_a_free_compartment_of_the_parcels_own_size_is_used_first) {
World w({Size::large, Size::medium, Size::small});
const Receipt receipt = w.put(Size::small);
LLD_CHECK_EQ(receipt.compartment, CompartmentNumber{3});
LLD_CHECK(!receipt.upgraded);
}
LLD_TEST(ac_7_2_when_its_size_is_full_a_parcel_goes_up_one_size_not_straight_to_the_largest) {
World w({Size::large, Size::medium, Size::small, Size::medium});
static_cast<void>(w.put(Size::small));
const Receipt receipt = w.put(Size::small, "bob");
LLD_CHECK_EQ(receipt.compartment, CompartmentNumber{2}); // lowest-numbered medium
LLD_CHECK(receipt.upgraded);
LLD_CHECK_EQ(w.bank.compartment(2).state(), CompartmentState::occupied);
LLD_CHECK_EQ(w.bank.parcel(receipt.parcel).info().size, Size::small); // its own size is kept
}
LLD_TEST(ac_7_3_when_the_next_size_is_full_too_it_goes_up_again) {
World w({Size::small, Size::medium, Size::large});
static_cast<void>(w.put(Size::small));
static_cast<void>(w.put(Size::medium));
const Receipt receipt = w.put(Size::small, "bob");
LLD_CHECK_EQ(receipt.compartment, CompartmentNumber{3});
LLD_CHECK(receipt.upgraded);
// Nothing of medium size or larger is left now.
LLD_CHECK_EQ(refusal_of(w.courier.deposit({"carol", Size::medium})), DepositRefusal::no_free_compartment);
}
LLD_TEST(ac_7_4_the_cost_an_upgraded_parcel_can_crowd_out_a_larger_one) {
World w({Size::small, Size::large});
static_cast<void>(w.put(Size::small));
LLD_CHECK(w.put(Size::small, "bob").upgraded);
LLD_CHECK_EQ(refusal_of(w.courier.deposit({"carol", Size::large})), DepositRefusal::no_free_compartment);
}
LLD_TEST(ac_7_5_upgrading_skips_closed_compartments_and_an_exact_fit_is_not_an_upgrade) {
World w({Size::small, Size::medium, Size::medium, Size::large});
static_cast<void>(w.put(Size::small));
LLD_CHECK(w.courier.take_out_of_service(2));
const Receipt receipt = w.put(Size::small, "bob");
LLD_CHECK_EQ(receipt.compartment, CompartmentNumber{3});
LLD_CHECK(receipt.upgraded);
LLD_CHECK(!w.put(Size::large, "carol").upgraded);
}

The notification tests use a Recorder that writes one line per event into a list shared by several listeners, so the order across listeners shows, and that can throw or read the bank when told:

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

test_step2.cpp
LLD_TEST(ac_8_1_every_listener_hears_every_event_in_the_order_they_were_added) {
World w;
std::vector<std::string> lines;
Recorder first(lines, "A");
Recorder second(lines, "B");
LLD_CHECK(w.bank.add_listener(first));
LLD_CHECK(w.bank.add_listener(second));
const Receipt a = w.put(Size::small);
static_cast<void>(w.put(Size::large));
static_cast<void>(w.customer.pick_up(a.code));
w.clock.advance(hold);
static_cast<void>(w.courier.collect_expired());
const std::vector<std::string> expected = {
"A deposited 1@1", "B deposited 1@1", "A deposited 2@4", "B deposited 2@4",
"A picked_up 1@1", "B picked_up 1@1", "A expired 2@4", "B expired 2@4"};
LLD_CHECK(lines == expected);
}
LLD_TEST(ac_8_2_events_carry_the_facts_of_the_change) {
World w({Size::small, Size::medium});
Keeper keeper;
w.bank.add_listener(keeper);
static_cast<void>(w.put(Size::small, "alice"));
const Receipt b = w.put(Size::small, "bob"); // upgraded to medium
w.clock.advance(1h);
static_cast<void>(w.customer.pick_up(b.code));
LLD_CHECK_EQ(keeper.deposits.size(), std::size_t{2});
if (keeper.deposits.size() == 2) {
const Deposited& d = keeper.deposits[1];
LLD_CHECK_EQ(d.parcel, b.parcel);
LLD_CHECK_EQ(d.compartment, CompartmentNumber{2});
LLD_CHECK_EQ(d.recipient, std::string("bob"));
LLD_CHECK_EQ(d.code, b.code);
LLD_CHECK(d.expires_at == b.expires_at);
LLD_CHECK(d.upgraded);
LLD_CHECK(!keeper.deposits[0].upgraded);
}
LLD_CHECK_EQ(keeper.pickups.size(), std::size_t{1});
if (!keeper.pickups.empty()) {
LLD_CHECK_EQ(keeper.pickups[0].parcel, b.parcel);
LLD_CHECK_EQ(keeper.pickups[0].compartment, CompartmentNumber{2});
LLD_CHECK_EQ(keeper.pickups[0].recipient, std::string("bob"));
LLD_CHECK(keeper.pickups[0].at == start + 1h);
}
w.clock.advance(hold); // alice's time is up 1 hour ago
static_cast<void>(w.bank.expire_overdue());
LLD_CHECK_EQ(keeper.expiries.size(), std::size_t{1});
if (!keeper.expiries.empty()) {
LLD_CHECK_EQ(keeper.expiries[0].recipient, std::string("alice"));
LLD_CHECK_EQ(keeper.expiries[0].compartment, CompartmentNumber{1});
LLD_CHECK(keeper.expiries[0].at == start + 1h + hold); // when noticed, not when due
}
}
LLD_TEST(ac_8_3_listeners_are_called_after_the_change_is_complete) {
World w;
std::vector<std::string> lines;
Recorder spy(lines, "S");
spy.bank = &w.bank;
w.bank.add_listener(spy);
const Receipt a = w.put(Size::small);
const Receipt b = w.put(Size::small);
static_cast<void>(w.customer.pick_up(a.code));
w.clock.advance(hold);
static_cast<void>(w.customer.pick_up(b.code));
const std::vector<std::string> expected = {"deposited/occupied", "deposited/occupied",
"picked up/free", "expired/occupied"};
LLD_CHECK(spy.seen_states == expected);
}
LLD_TEST(ac_8_4_a_listener_that_throws_changes_nothing_for_the_others_or_the_result) {
World w;
std::vector<std::string> lines;
Recorder broken(lines, "X");
broken.throws = true;
Recorder fine(lines, "F");
w.bank.add_listener(broken);
w.bank.add_listener(fine);
const Receipt a = w.put(Size::small); // the deposit still returns its receipt
LLD_CHECK_EQ(a.compartment, CompartmentNumber{1});
LLD_CHECK(std::holds_alternative<Opened>(w.customer.pick_up(a.code)));
LLD_CHECK_EQ(w.bank.parcel(a.parcel).state(), ParcelState::picked_up);
const std::vector<std::string> expected = {"X deposited 1@1", "F deposited 1@1",
"X picked_up 1@1", "F picked_up 1@1"};
LLD_CHECK(lines == expected);
LLD_CHECK_EQ(w.bank.listener_failures(), std::size_t{2});
}
LLD_TEST(ac_8_5_a_removed_listener_hears_nothing_and_the_list_has_no_duplicates) {
World w;
std::vector<std::string> lines;
Recorder r(lines, "R");
LLD_CHECK(w.bank.add_listener(r));
LLD_CHECK(!w.bank.add_listener(r)); // already there: not added twice
static_cast<void>(w.put(Size::small));
LLD_CHECK_EQ(lines.size(), std::size_t{1});
LLD_CHECK(w.bank.remove_listener(r));
LLD_CHECK(!w.bank.remove_listener(r));
static_cast<void>(w.put(Size::small));
LLD_CHECK_EQ(lines.size(), std::size_t{1});
}
// A listener that tries to change the list while it is being told.
struct Meddler final : LockerListener {
LockerBank* bank = nullptr;
LockerListener* other = nullptr;
void on_deposited(const Deposited&) override { bank->add_listener(*other); }
void on_picked_up(const PickedUp&) override { bank->remove_listener(*this); }
};
LLD_TEST(ac_8_6_changing_the_listener_list_from_inside_a_listener_is_refused) {
World w;
std::vector<std::string> lines;
Recorder late(lines, "L");
Meddler meddler;
meddler.bank = &w.bank;
meddler.other = &late;
w.bank.add_listener(meddler);
const Receipt a = w.put(Size::small);
static_cast<void>(w.customer.pick_up(a.code));
LLD_CHECK_EQ(w.bank.listener_failures(), std::size_t{2}); // both attempts threw logic_error
LLD_CHECK(lines.empty()); // late was never added
LLD_CHECK(w.bank.remove_listener(meddler)); // and meddler is still there
LLD_CHECK(w.bank.add_listener(late)); // outside events it works
}
LLD_TEST(ac_8_7_refused_and_failed_operations_send_no_event) {
World w({Size::small}, {"111111"});
Keeper keeper;
w.bank.add_listener(keeper);
const Receipt a = w.put(Size::small);
LLD_CHECK_EQ(refusal_of(w.courier.deposit({"bob", Size::small})), DepositRefusal::no_free_compartment);
static_cast<void>(w.customer.pick_up(a.code));
LLD_CHECK_THROWS(w.courier.deposit({"bob", Size::small}), std::out_of_range); // codes ran out
LLD_CHECK_EQ(refusal_of(w.customer.pick_up("999999")), PickupRefusal::unknown_code);
LLD_CHECK_EQ(refusal_of(w.customer.pick_up(a.code)), PickupRefusal::code_already_used);
LLD_CHECK_EQ(keeper.deposits.size(), std::size_t{1});
LLD_CHECK_EQ(keeper.pickups.size(), std::size_t{1});
LLD_CHECK(keeper.expiries.empty());
}
LLD_TEST(ac_8_8_a_parcel_expires_once_and_its_event_is_sent_once) {
World w;
Keeper keeper;
w.bank.add_listener(keeper);
const Receipt a = w.put(Size::small);
w.clock.advance(hold);
static_cast<void>(w.customer.pick_up(a.code)); // expires here
static_cast<void>(w.customer.pick_up(a.code)); // already expired
static_cast<void>(w.bank.expire_overdue());
static_cast<void>(w.courier.collect_expired()); // returned, not expired again
LLD_CHECK_EQ(keeper.expiries.size(), std::size_t{1});
LLD_CHECK_EQ(w.bank.parcel(a.parcel).state(), ParcelState::returned);
}
// A listener that calls back into the bank: told about a deposit, it picks
// the parcel up at once, which sends a second round of events inside the
// first. When that inner round is over, it tries to add a listener.
struct EagerCustomer final : LockerListener {
CustomerAccess* customer = nullptr;
LockerBank* bank = nullptr;
LockerListener* other = nullptr;
void on_deposited(const Deposited& e) override {
static_cast<void>(customer->pick_up(e.code));
bank->add_listener(*other); // the outer round is still running: refused
}
};
LLD_TEST(ac_8_9_a_listener_that_calls_back_into_the_bank_starts_a_nested_round) {
World w;
std::vector<std::string> lines;
EagerCustomer eager;
Recorder later(lines, "L");
Recorder never(lines, "N");
eager.customer = &w.customer;
eager.bank = &w.bank;
eager.other = &never;
w.bank.add_listener(eager);
w.bank.add_listener(later);
const Receipt a = w.put(Size::small);
LLD_CHECK_EQ(w.bank.parcel(a.parcel).state(), ParcelState::picked_up);
// The depth counter is still above 0 after the inner round, so the add
// was refused (a true/false flag would have been cleared by then).
LLD_CHECK_EQ(w.bank.listener_failures(), std::size_t{1});
// The limitation: the later listener hears the inner event first.
const std::vector<std::string> expected = {"L picked_up 1@1", "L deposited 1@1"};
LLD_CHECK(lines == expected);
LLD_CHECK(w.bank.add_listener(never)); // after both rounds the list may change
}

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

main.cpp
// CS-16 step 2 demo: the step 1 story with the two changes: a parcel put
// in a larger compartment when its size is full, and listeners that are
// told about deposits, pickups, and expiries.
#include <chrono>
#include <iostream>
#include <stdexcept>
#include <string>
#include <variant>
#include <vector>
#include "locker_bank.hpp"
using namespace locker;
using namespace std::chrono;
namespace {
const TimePoint start = sys_days{2026y / 3 / 2} + 9h;
// Times are shown as hours and minutes since the demo began.
std::string since_start(TimePoint t) {
const auto passed = duration_cast<minutes>(t - start);
return "+" + std::to_string(passed.count() / 60) + "h" + std::to_string(passed.count() % 60) + "m";
}
// Sends the code to the recipient. Here "sending" is printing; a real
// one would hand the message to an SMS or e-mail service.
class TextMessages final : public LockerListener {
public:
void on_deposited(const Deposited& e) override {
std::cout << " [sms to " << e.recipient << "] your parcel is in compartment " << e.compartment
<< ", code " << e.code << ", until " << since_start(e.expires_at) << '\n';
}
void on_expired(const Expired& e) override {
std::cout << " [sms to " << e.recipient << "] your parcel was not collected in time"
<< " and will be sent back\n";
}
};
// A record for staff. It never writes the code down.
class AuditLog final : public LockerListener {
public:
void on_deposited(const Deposited& e) override {
std::cout << " [log] parcel " << e.parcel.value << " in " << e.compartment
<< (e.upgraded ? " (larger than needed)" : "") << '\n';
}
void on_picked_up(const PickedUp& e) override {
std::cout << " [log] parcel " << e.parcel.value << " picked up from " << e.compartment << '\n';
}
void on_expired(const Expired& e) override {
std::cout << " [log] parcel " << e.parcel.value << " expired in " << e.compartment << '\n';
}
};
// A listener with a bug: it throws on every pickup.
class BrokenScreen final : public LockerListener {
public:
void on_picked_up(const PickedUp&) override { throw std::runtime_error("screen offline"); }
};
// Deposits a parcel and prints what happened.
void drop_off(CourierAccess& courier, const std::string& recipient, Size size) {
std::cout << "deposit " << to_string(size) << " for " << recipient << '\n';
const DepositResult result = courier.deposit(ParcelInfo{recipient, size});
// std::get_if gives a pointer to the refusal if that is what the
// variant holds, and nullptr if it holds a Receipt.
if (const auto* refusal = std::get_if<DepositRefusal>(&result)) {
std::cout << " refused (" << to_string(*refusal) << ")\n";
}
}
// Tries a code and prints both what the bank knows and what the screen shows.
void try_code(CustomerAccess& customer, const std::string& who, const std::string& code) {
std::cout << who << " enters " << code << '\n'; // first, so listener output comes after
const PickupResult result = customer.pick_up(code);
if (const auto* opened = std::get_if<Opened>(&result)) {
std::cout << " compartment " << opened->compartment << " opens\n";
return;
}
const PickupRefusal refusal = std::get<PickupRefusal>(result);
std::cout << " refused, log says \"" << to_string(refusal) << "\", screen says \""
<< customer_message(refusal) << "\"\n";
}
void show(const LockerBank& bank) {
for (const Compartment& c : bank.compartments()) {
std::cout << " " << c.number() << " " << to_string(c.size()) << ": " << to_string(c.state());
if (const auto id = c.parcel()) {
const Parcel& p = bank.parcel(*id);
std::cout << " (" << p.info().recipient << ", " << to_string(p.state()) << ")";
}
std::cout << '\n';
}
}
} // namespace
int main() {
// The clock, code source, and listeners are made first so they outlive
// the bank, which keeps pointers to them.
ManualClock clock{start};
ScriptedCodes codes{{"482913", "730154", "119806", "604327", "258461"}};
TextMessages texts;
AuditLog log;
BrokenScreen screen;
LockerBank bank({Size::small, Size::small, Size::medium, Size::large}, 48h, clock, codes);
bank.add_listener(texts);
bank.add_listener(log);
bank.add_listener(screen);
CourierAccess courier{bank};
CustomerAccess customer{bank};
drop_off(courier, "alice", Size::small);
drop_off(courier, "bob", Size::small);
drop_off(courier, "carol", Size::small); // small ones taken: goes in the medium one
drop_off(courier, "dave", Size::small); // medium taken too: goes in the large one
drop_off(courier, "erin", Size::large); // the cost: no room left for a large parcel
show(bank);
clock.advance(2h);
try_code(customer, "alice", "482913");
try_code(customer, "alice", "482913"); // the same code a second time
std::cout << "listener failures: " << bank.listener_failures() << '\n';
bank.remove_listener(screen); // the broken screen is taken off the list
clock.advance(46h); // now exactly 48 hours after the deposits
try_code(customer, "bob", "730154");
const std::vector<Opened> collected = courier.collect_expired();
std::cout << "courier collects:";
for (const Opened& o : collected) std::cout << " compartment " << o.compartment;
std::cout << '\n';
show(bank);
// No need to remove texts and log: the bank was declared after them,
// so it is destroyed first and never calls a destroyed listener.
}
Expected output
deposit small for alice
[sms to alice] your parcel is in compartment 1, code 482913, until +48h0m
[log] parcel 1 in 1
deposit small for bob
[sms to bob] your parcel is in compartment 2, code 730154, until +48h0m
[log] parcel 2 in 2
deposit small for carol
[sms to carol] your parcel is in compartment 3, code 119806, until +48h0m
[log] parcel 3 in 3 (larger than needed)
deposit small for dave
[sms to dave] your parcel is in compartment 4, code 604327, until +48h0m
[log] parcel 4 in 4 (larger than needed)
deposit large for erin
refused (no free compartment of that size or larger)
1 small: occupied (alice, deposited)
2 small: occupied (bob, deposited)
3 medium: occupied (carol, deposited)
4 large: occupied (dave, deposited)
alice enters 482913
[log] parcel 1 picked up from 1
compartment 1 opens
alice enters 482913
refused, log says "code already used", screen says "This code cannot be used. Check it, or contact customer service."
listener failures: 1
bob enters 730154
[sms to bob] your parcel was not collected in time and will be sent back
[log] parcel 2 expired in 2
refused, log says "code expired", screen says "This code cannot be used. Check it, or contact customer service."
[sms to carol] your parcel was not collected in time and will be sent back
[log] parcel 3 expired in 3
[sms to dave] your parcel was not collected in time and will be sent back
[log] parcel 4 expired in 4
courier collects: compartment 2 compartment 3 compartment 4
1 small: free
2 small: free
3 medium: free
4 large: free

Read it against the rules:

  • Carol and dave go up one size each, and the log says “(larger than needed)”. Erin’s large parcel is refused: the cost, shown.
  • On alice’s pickup, the log line comes before “compartment 1 opens”: listeners run inside pick_up, after the change and before it returns. The broken screen’s exception is counted, not seen.
  • The second try with alice’s code sends no event (AC-8.7).
  • At +48h0m, bob’s attempt expires parcel 2 and sends one on_expired to each remaining listener. The courier’s collection then expires carol’s and dave’s, with their events, and collects all three.
  • The broken screen was removed after the first round, so it hears nothing more.

A parcel locker is a common intermediate question because it looks like a parking lot and is not: the codes, the expiry, and the roles are where the real decisions are. A plan for 45 minutes, using the time boxes from The delivery framework:

Time What to do What to say
About 5 min Ask about sizes, which door a parcel gets, how codes reach the customer, how long they work, and who may do what. “When every small door is full, does the courier take the parcel back, or does it go in a bigger one?”
5 min Sketch the bank, compartments, parcel records, and the two roles. Draw both state machines. “A compartment cannot go out of service while a parcel is inside.”
10–15 min Write find_free, deposit, and pick_up, in that order. “Everything that can fail comes before the first change.”
10 min Trace a run: a full size, a reused code, a wrong code, the expiry moment. Name the tests. “At exactly the expiry time the code no longer works, and a test pins that second.”
About 5 min Take a change: a larger door when a size is full, or notifications. “Listeners are told after the change, and the bank does not own them.”

What is usually expected at each level

Level Usually expected
Junior Compartments with sizes; a deposit that finds a free one of the right size; a code that opens it once; expiry; refusals with reasons; a few tests.
Mid-level All of the above, plus: smallest fit with a stated tie-break; two state machines; injected clock and code source; the expiry boundary decided and tested; one screen message; a deposit that is all or nothing.
Senior All of the above, plus: why sequential or seeded codes are unsafe and what a real source, rate limit, and hashing need; roles kept apart by the type system and why that is not authentication; the cost of upgrading; Observer’s lifetime and re-entrancy rules, and when one callback is enough; what changes with several screens or a server.

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

How this code works: Interview questions, with short answers
  1. Why not give the parcel the first free compartment that fits? Because small parcels then use up the large compartments, and large parcels are refused while small doors stand empty. Smallest fit keeps each size for parcels that need it.
  2. Why keep a record after the parcel is picked up? To refuse a reused code with its real reason, and to make sure the same code is never given to a later parcel, which would let the first customer open the second customer’s door.
  3. Why do the caller and the screen see different things? The caller (log, support) needs the exact reason. A stranger at the screen must not learn whether a guessed code was real.
  4. Why is the clock an interface? So a test can stand at exactly the expiry time, and one second before, without waiting 48 hours.
  5. What if the code source throws in the middle of a deposit? Nothing has changed yet, because codes are drawn before the first change. The exception reaches the courier’s caller and the bank is as it was (AC-2.4).
  6. Does CourierAccess stop a customer from collecting parcels? It stops code written for the customer’s screen from calling courier operations, because the functions are not there. It does not prove who someone is; that is authentication, done elsewhere.
  7. Why not shared_ptr for listeners? The bank does not need to keep a listener alive; it needs the listener to stay alive while registered. Shared ownership hides that question and invites cycles. A plain pointer with one stated rule, or a subscription object that removes itself, says it directly.
  8. Two screens on one bank? Then deposit and pick_up race: two deposits could choose the same free compartment. One mutex around each operation of the bank would be the first step; see the limitations below.

This is a teaching model. A real locker system would also need:

  • Concurrency. The bank is single-threaded and says so. Several screens, a courier’s handheld, and a timer on other threads would race on the same compartments, and need at least a lock around every operation, and listeners called outside that lock.
  • Persistence. Everything is in memory in one process. A power cut loses every code and record, while the parcels are still behind the doors. A real bank stores each change before it opens a door.
  • Secure codes. No secure random source, no rate limit on wrong codes, and codes stored in plain text. The comment in codes.hpp says what is missing.
  • Identity. Nothing checks who a courier is. The two roles are kept apart in code, not by login.
  • The door itself. Opened is returned and the record says “picked up”, but nothing confirms the door opened, or that the parcel was taken. A jammed door would leave the record wrong.
  • Growth. Records are never deleted and codes are found by a linear search. Fine for a sketch; a real bank keeps an index and deletes old records.
  • Slow listeners. Listeners run inside the operation, on the same thread, so a slow text-message service would freeze the screen. A real bank would put events on a queue and send them elsewhere. Listener failures are only counted, not logged or retried.
  • Re-entrancy. A listener that calls back into the bank changes the order of events, as described above. A test pins that behaviour; it is not fixed.
  • Time. system_clock can jump when the machine’s clock is corrected, which can expire a code early or late. Time zones only matter for what the screen shows, which is out of scope.
  • One bank. A network of banks, moving a parcel to another bank, and payments are out of scope.
Requirement Design element Code Tests Status
FR-1 assignment find_free, smallest size, lowest number step 1 locker_bank.cpp ac_1_1_… to ac_1_6_… Tested
FR-2 codes CodeSource, three draws, find_by_code over all records step 1 codes.hpp, locker_bank.cpp ac_2_1_… to ac_2_4_… Tested
FR-3 pickup pick_up, ParcelState::picked_up, release step 1 locker_bank.cpp ac_3_1_… to ac_3_3_… Tested
FR-4 expiry Clock, is_overdue with >=, expire_overdue, collect_expired step 1 parcel.hpp, locker_bank.cpp ac_3_4_…, ac_3_5_…, ac_4_2_… to ac_4_4_… Tested
FR-5 roles private operations, CourierAccess, CustomerAccess step 1 locker_bank.hpp ac_4_1_… (concepts) Tested
FR-6 compartments compartment table, take_out_of_service step 1 compartment.hpp, locker_bank.cpp ac_1_5_…, ac_4_5_…, ac_5_1_… Tested
INV-2 legal moves can_move, move, move_to step 1 compartment.hpp, parcel.hpp ac_5_1_… to ac_5_3_… Tested
NFR-1 no leaks customer_message step 1 locker_bank.cpp ac_3_6_… Tested
NFR-2 all or nothing order of steps in deposit, static_assert step 1 locker_bank.cpp ac_1_3_…, ac_2_3_…, ac_2_4_… Tested
NFR-3 testable ManualClock, ScriptedCodes step 1 clock.hpp, codes.hpp every test Tested
NFR-4 one thread no locks; stated on this page none none: a statement, not a behaviour Stated
Change: size upgrade all_sizes, find_free size loop, Receipt::upgraded step 2 types.hpp, locker_bank.cpp ac_7_1_… to ac_7_5_…, ac_1_3_… Tested
Change: notifications LockerListener, events, notify, listener list step 2 events.hpp, locker_bank.* ac_8_1_… to ac_8_9_… Tested

Exercise: Keep the last large compartment for a large parcel

The step 2 demo shows the cost of the upgrade rule: dave’s small parcel took the only large compartment, and erin’s large parcel was refused. Change the rule so that a parcel smaller than large never takes the last free large compartment. Start from step 2.

  1. Where does the new rule go, and what does it need to know?
  2. Write it, and a test with the layout small, large, large.
  3. Run the step 2 tests. Which existing tests fail, and is that a bug?
  4. What does the new rule cost?
Show the explained answer
  1. In find_free, in the size loop. The rule is about which sizes a parcel may try, so it belongs where sizes are tried. It needs to know how many large compartments are free, and free_count already answers that.

  2. The code:

    IllustrativeA fragment for explanation; not compiled on its own.

    for (const Size candidate : all_sizes) {
    if (candidate < size) continue; // too small for this parcel
    // New: a parcel smaller than large may use a large compartment
    // only if at least one other large one stays free after it.
    if (candidate == Size::large && size != Size::large && free_count(Size::large) <= 1) {
    continue;
    }
    for (Compartment& c : compartments_) {
    if (c.size() == candidate && c.state() == CompartmentState::free) return &c;
    }
    }
    return nullptr;

    And the test:

    IllustrativeA fragment for explanation; not compiled on its own.

    LLD_TEST(exercise_the_last_large_compartment_is_kept_for_a_large_parcel) {
    World w({Size::small, Size::large, Size::large});
    static_cast<void>(w.put(Size::small));
    const Receipt bob = w.put(Size::small, "bob"); // two large free: one may be used
    LLD_CHECK_EQ(bob.compartment, CompartmentNumber{2});
    LLD_CHECK(bob.upgraded);
    // Only one large is free now, so a small parcel is refused...
    LLD_CHECK_EQ(refusal_of(w.courier.deposit({"carol", Size::small})),
    DepositRefusal::no_free_compartment);
    // ...and a large parcel still gets it.
    LLD_CHECK_EQ(w.put(Size::large, "dave").compartment, CompartmentNumber{3});
    }
  3. Three tests fail: ac_1_5, ac_7_3, and ac_7_4. Each puts a smaller parcel into the only free large compartment, which the new rule forbids. That is not a bug in the new code: those tests pinned the old rule, and the rule has changed on purpose. Update them to the new expectation (for example, ac_7_4 now shows the large parcel getting in and the small one refused), and keep one test that shows the new cost.

  4. The cost moves, it does not vanish. Now a small parcel is turned away while a large compartment stands empty, which was the complaint the upgrade rule fixed. Which refusal is worse depends on how many large parcels arrive, which is a question to take back to the team, with the upgraded counts from the log as evidence.

This answer was checked in a scratch copy of step 2; it is not part of the example in the repository. With the change, the new test passed, and exactly the three tests named above failed, under GCC 11.4, Clang 14, and GCC with AddressSanitizer and UndefinedBehaviorSanitizer.

  • Follow the framework: requirements, entities, classes, code, then the change. The questions about sizes, codes, and roles decided the shape before any code.
  • Smallest fit, lowest number. Say the tie-break, and test it.
  • Write each life cycle as a table of legal moves, checked in one place. The missing arrow (occupied to out of service) is a rule.
  • Inject the clock and the code source. Tests then stand on the boundary to the second and know every code.
  • Valid up to, not at. Decide the boundary once and test both sides.
  • Exact reasons for the program, one message for the screen.
  • Build everything, then commit in one step, and let a static_assert guard the assumption the commit relies on.
  • Roles through access classes are checked by the compiler, and are not authentication.
  • Observer earns its place with several independent listeners, and brings a lifetime rule, a rule about the list, and exception handling. For one listener, one callback is enough.