Use cases, user stories, and acceptance criteria
What you will learn on this page
Section titled “What you will learn on this page”- How to write a use case: an actor’s goal, the main flow, and the alternate flows.
- How a use-case diagram shows which actors take part in which use cases.
- What a user story is, and how it differs from a use case.
- How to write acceptance criteria as Given/When/Then, with concrete values.
- How each criterion becomes one named C++ test.
Why requirements need scenarios
Section titled “Why requirements need scenarios”The requirements lesson produced a list: FR-1 to FR-9. Each is checkable on its own. But a user at a printer does not experience FR-2, FR-3, FR-4, and FR-8 separately. They badge in, and several requirements apply at once, in some order. Questions appear only when you put them together: if Kim’s first job does not fit her quota, does her second job still print?
A use case describes one interaction from start to finish: an actor (a person or outside system) with a goal, the steps when everything goes right, and the steps when something does not. It is the requirements version of the sequence diagrams from the modeling section, written before the classes exist.
The naive version
Section titled “The naive version”Story: As a user, I want to print. Acceptance: Printing works.
This says nothing a test can check. It does not say who the user is, what “print” means here (submitting, releasing?), or what happens when anything goes wrong. Most of the design questions live in the cases this leaves out.
The use cases of the print-release service
Section titled “The use cases of the print-release service”Text description of the diagram
Inside the print-release service are five use cases. The print server takes part in UC-1, hold a submitted job. A staff member takes part in UC-2, release held jobs, and the badge system also takes part in UC-2, to say who owns the badge. The clock takes part in UC-3, delete expired jobs. The facilities manager takes part in UC-4, grant extra pages, and UC-5, set a user’s quota.
Diagram source (Mermaid)
flowchart LR
PS([Print server])
Staff([Staff member])
BS([Badge system])
Clock([Clock])
Fac([Facilities manager])
subgraph service [Print-release service]
UC1((UC-1 Hold a submitted job))
UC2((UC-2 Release held jobs))
UC3((UC-3 Delete expired jobs))
UC4((UC-4 Grant extra pages))
UC5((UC-5 Set a user's quota))
end
PS --- UC1
Staff --- UC2
UC2 --- BS
Clock --- UC3
Fac --- UC4
Fac --- UC5A use-case diagram is a table of contents. Actors are drawn outside the system’s box, use cases (the ovals) inside, and a line means “takes part in”. Actors on the left usually start the use case; the badge system on the right only helps. The clock is an actor too: nobody presses a button to expire jobs, but something starts UC-3 every so often.
The diagram is deliberately thin. It does not show steps, order, or rules. Its value is in what it lets you check: every outside party from the context diagram appears, and every in-scope item (S1 to S6) is covered by a use case. Two choices were made here. The printer is not drawn as an actor, because it only passes on the staff member’s badge read; it is the staff member’s channel. The clock is added, because it starts UC-3 but is not an outside system. S5, printer failures, does not have its own use case: it is an alternate flow of UC-2.
Writing a use case
Section titled “Writing a use case”Here is UC-2 in full. A written use case has a few standard parts; the flows are the important ones.
UC-2 Release held jobs
- Primary actor: a staff member.
- Supporting actor: the badge system.
- Goal: collect their own printed pages at the printer they are standing at.
- Precondition: the user has a badge.
- Trigger: the user badges in at a printer.
Main flow (everything goes right):
- The printer sends the badge ID and its printer ID to the service.
- The service asks the badge system who owns the badge, and gets a user.
- The service finds the user’s held jobs, oldest first.
- For each job, the service checks that its pages fit in the user’s remaining quota, and charges them.
- The service sends the job to the print server, for this printer, and stops holding it.
- The printer’s panel says how many jobs are printing.
Alternate flows (numbered by the step where they branch):
- 2a. The badge is not known. Nothing is printed. The panel says “Badge not recognised.” The use case ends.
- 3a. The user has no held jobs. The panel says “No jobs waiting.” The use case ends.
- 4a. A job does not fit in the remaining quota. That job is not printed, is not charged, and stays held. The service continues with the next job. The panel says how many jobs were not printed, and why.
- 5a. The printer jams or goes offline during a job. The pages not printed must not be lost (FR-9). Designed in the invariants and failures lesson.
- *a. The badge system does not answer (at any step that needs it). Nothing is printed (Q17). Designed in the invariants and failures lesson.
Postconditions: each of the user’s held jobs has either been printed and charged, or is still held and not charged. No other user’s job has changed.
Requirements covered: FR-2, FR-3, FR-4, FR-8, FR-9; NFR-1, NFR-3.
What writing it revealed
Section titled “What writing it revealed”Writing step 4 and flow 4a forced two questions the requirements did not answer:
- Does a refused job stay held? FR-4 says it is not printed, but not what happens to it. The working answer is “yes, until it expires, so it can print after facilities grants extra pages”. That is assumption A5 (Q20) in the assumption register.
- Do later jobs still print? If Kim has a 30-page job and then a 5-page job, with 20 pages left, does the 5-page job print? Shown the use case, the facilities manager answered: yes, each job is judged on its own (Q22, confirmed).
The *a flow is written with a star because it can happen at any step. The
postcondition is useful for testing: it is what every flow, normal or not,
must leave true.
User stories
Section titled “User stories”A user story is a short statement of what someone needs and why:
As a role, I want something, so that benefit.
For the print-release service:
- As a staff member, I want my jobs to wait until I badge in, so that nobody else picks up my pages.
- As a staff member, I want to release my jobs at whichever printer is nearest, so that I don’t have to walk to a particular floor.
- As the facilities manager, I want to grant a user extra pages, so that someone with an urgent need is not blocked by their quota.
A story is smaller and less formal than a use case. It is a placeholder for a conversation: it names who, what, and why, and leaves the details to its acceptance criteria. The “so that” part matters most, because it connects the story to a goal (the first story serves G2). A story without a benefit is a feature request without a reason.
Use cases or stories? Teams often use stories to plan work and use cases when an interaction has many alternate flows. They work well together: the three stories above all live inside UC-2 and UC-4, and UC-2’s alternate flows supply their acceptance criteria.
Acceptance criteria: Given / When / Then
Section titled “Acceptance criteria: Given / When / Then”An acceptance criterion says when a story or flow works, in a form a test can follow:
- Given the starting situation, with concrete values;
- When one event happens;
- Then the observable results, including what must not change.
These are the criteria for the service’s use cases. Each has an ID, so that tests and requirements can refer to it.
| ID | Flow | Given | When | Then |
|---|---|---|---|---|
| AC-1.1 | UC-1 | the print server reports a 12-page job for Robin | it is held | nothing prints; it is listed in Robin’s held jobs and nobody else’s |
| AC-1.2 | UC-1 | the print server reports a job with 0 pages | it is held | it is rejected |
| AC-2.1 | main | Robin holds jobs of 12 and 3 pages, with 500 pages left | Robin badges in at 2-East | both print at 2-East, oldest first; Robin has 485 pages left; Robin has no held jobs |
| AC-2.2 | 2a | a held job, and a badge the badge system does not know | the badge is used | nothing prints; the job is still held; the panel says “Badge not recognised.” |
| AC-2.3 | 3a | Robin has no held jobs | Robin badges in | the panel says “No jobs waiting.” |
| AC-2.4 | 4a | Kim has 20 pages left and holds a 30-page job | Kim badges in | it does not print; it is still held; Kim still has 20 pages; the panel says the quota is exceeded |
| AC-2.5 | 4a | Kim has 20 pages left and holds jobs of 30, then 5 pages | Kim badges in | only the 5-page job prints; the 30-page job is still held; Kim has 15 pages left |
| AC-2.6 | main | Robin and Kim both hold jobs | Robin badges in | only Robin’s job prints; Kim’s job is still held |
| AC-2.7 | main | Robin holds a job | Robin badges in at 3-West | it prints at 3-West (added later, by the traceability lesson) |
| AC-3.1 | UC-3 | jobs held for exactly 24 hours and for 23 hours 59 minutes | the expiry check runs | the first is deleted and can no longer be released; the second is kept |
| AC-4.1 | UC-4 | Kim’s 30-page job was refused with 20 pages left | facilities grants 20 pages, and Kim badges in again | the job prints; Kim has 10 pages left |
| AC-4.2 | UC-4 | Kim was granted 50 extra pages this month | a new month starts | Kim has exactly the normal 500 pages (assumption A6) |
What makes these good criteria:
- Concrete values. “20 pages left and a 30-page job”, not “a user over quota”. The numbers make the test obvious, and they make edges visible: what if the job is exactly 20 pages? (It fits: “fit” means “not more than what is left”. A test for that edge is a good addition.)
- One event per criterion. AC-4.1 has two actions in its When; it is still one scenario, because the point is the second badge-in after the grant.
- What does not change. AC-2.2 and AC-2.4 check that nothing printed and that the jobs are still held; AC-2.4 also checks that the quota stayed the same. Refusals are where bugs hide, as the state machine lesson’s refused cells showed.
- The domain’s words. “Held”, “badges in”, “pages left”, not “the vector is empty”.
- Traced. Each criterion belongs to a flow, and each flow to a use case and its requirements. AC-1.2 is the exception worth noticing: no FR asks for it. It protects assumption A8 (page counts are correct), because a job with no pages means the count is wrong. A criterion with no requirement is either a missing requirement or a guess; here it is recorded against A8.
From criteria to code
Section titled “From criteria to code”The example implements UC-1 to UC-4 (UC-5, setting a quota, is left for the exercise and for the traceability lesson). The first part holds jobs:
VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// One document waiting at the print server: plain data with no rules of its// own, so a struct with public fields is enough. UserId is just a// std::string (see the `using` lines above), and Minutes is a// std::chrono::minutes, a count of minutes that cannot be mixed up with a// plain int by accident. The `= 0` and `{0}` give every field a starting// value, so a PrintJob is never full of garbage.struct PrintJob { int id = 0; // given by HeldJobs::hold, starting from 1 UserId owner; // the user who sent the job std::string document; // the file name, shown in the printer log int pages = 0; // what the job costs from the owner's quota Minutes submitted_at{0}; // when the print server reported it};
// Jobs reported by the print server, held until their owner releases them// (FR-1) or until they expire (FR-7). Owns the jobs by value: they live in// the vector below, so nothing needs to be freed by hand. Callers get copies// of jobs (from jobs_for), never pointers into the vector.class HeldJobs {public: // How long a job may wait before it is deleted. Written as 24 hours, but // stored as Minutes: std::chrono converts hours to minutes (1440) // exactly, at compile time, so no one has to multiply by 60 by hand. static constexpr Minutes hold_limit = std::chrono::hours{24};
// Holds a new job and returns its ID. Throws std::invalid_argument if // pages < 1: the print server should never report an empty job. // owner and document are taken by value, so they can be moved into the // stored job instead of copied a second time. int hold(UserId owner, std::string document, int pages, Minutes now);
// The owner's held jobs, oldest first (FR-3). Returns a new vector of // copies, so the caller may keep it even after jobs are removed here. [[nodiscard]] std::vector<PrintJob> jobs_for(const UserId& owner) const;
// Removes a job; returns false if no job has that ID. bool remove(int job_id);
// Deletes every job held for hold_limit or longer (FR-7); returns how many. int expire(Minutes now);
// jobs_.size() is an unsigned std::size_t; static_cast<int> turns it // into the plain int the rest of this class uses for counts. [[nodiscard]] int count() const { return static_cast<int>(jobs_.size()); }
private: // New jobs go on the end, so the vector is always in submission order. // That is oldest first, because the print server reports each job as it // arrives; jobs_for relies on this order and never sorts. std::vector<PrintJob> jobs_; // in submission order // The ID the next held job will get. It only ever goes up, so an ID is // never reused, even after its job has been printed or deleted. int next_id_ = 1;};HeldJobs owns the jobs by value, in submission order, which gives “oldest
first” (FR-3) without sorting. A std::vector searched from start to end is
more than fast enough for NFR-2’s 2,000 jobs. The 24-hour limit is a
constant here, and so is the 500-page default below; NFR-5 asks for both to
be data that facilities can change, which this small example does not do.
Minutes is a
std::chrono::minutes, so a duration can never be confused with a page count.
VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// Deletes every job that has waited 24 hours or more, and says how many went.// `now` is the current time on the same clock as submitted_at.int HeldJobs::expire(Minutes now) { // A lambda (a small unnamed function) that answers "has this job // expired?". [now] copies `now` into it so it can use it. hold_limit // needs no capture: it is a static member of the class. // `now - job.submitted_at` is how long the job has waited. `>=` means a // job held for exactly 24 hours is deleted (AC-3.1: "24 hours or more"). const auto expired = [now](const PrintJob& job) { return now - job.submitted_at >= hold_limit; }; // std::erase_if (C++20) removes every element the lambda says yes to, // keeps the others in their old order, and returns how many it removed // (a std::size_t, hence the static_cast to int). return static_cast<int>(std::erase_if(jobs_, expired));}The expiry rule (FR-7) is one comparison: held for hold_limit or longer.
AC-3.1 checks both sides of that edge.
VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// The pages a job uses from its owner's quota. Assumption A3 (Q8): a colour// page counts the same as a black-and-white page. If finance decides// otherwise, PrintJob gains a colour page count and only this function// (and its tests) change.// `inline` lets a function be defined in a header that several .cpp files// include, without the linker seeing it as defined twice.[[nodiscard]] inline int pages_charged(const PrintJob& job) { return job.pages; }
// One user's pages for the current month (FR-4, FR-5). It keeps three// numbers and works out what is left from them, rather than storing a// "remaining" number that could drift out of step with the others.class QuotaAccount {public: // `explicit` stops a plain int from turning into a QuotaAccount by // accident; you have to write QuotaAccount(500). explicit QuotaAccount(int monthly_pages) : monthly_pages_(monthly_pages) {}
// The month's allowance, plus any extra granted, minus what has been // used. For example 500 + 20 - 480 = 40. [[nodiscard]] int remaining() const { return monthly_pages_ + extra_pages_ - used_pages_; }
// Charges the pages if they all fit; otherwise changes nothing. Returns // true if the pages were charged. [[nodiscard]] because ignoring the // answer would mean printing without knowing whether it was paid for. [[nodiscard]] bool try_charge(int pages);
// Facilities gives the user more pages for this month only (FR-5). void grant_extra(int pages) { extra_pages_ += pages; }
// Assumption A6 (Q21): extra pages do not carry into the next month. // Both counters go back to zero; the monthly allowance stays the same. void start_new_month() { used_pages_ = 0; extra_pages_ = 0; }
private: int monthly_pages_; // the normal allowance, fixed when the account is made int extra_pages_ = 0; // granted this month by facilities int used_pages_ = 0; // charged this month by printed jobs};
// Every user's account. A user without an account gets the default quota// the first time it is needed.class Quotas {public: explicit Quotas(int default_monthly_pages) : default_pages_(default_monthly_pages) {}
// Returns the user's account, creating it with the default allowance if // it does not exist yet, so this never fails. It returns a reference (&): // the caller changes the account stored here, not a copy of it. // The reference stays valid while this Quotas lives: std::map never // moves its elements when others are added. QuotaAccount& account_for(const UserId& user);
private: int default_pages_; // One account per user ID, looked up by the ID. Quotas owns the // accounts by value. std::map<UserId, QuotaAccount> accounts_;};QuotaAccount::try_charge changes nothing when the pages do not fit, which is
exactly what AC-2.4 asks. pages_charged is where assumption A3 lives.
Quotas::account_for returns a reference into a std::map, which stays valid
while the Quotas object lives, because a map never moves its elements when
others are added.
The badge system and print server are outside the boundary, so the service reaches them through two small interfaces:
VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// The outside systems from the context diagram, seen from inside the// boundary. Production code would implement these with the real badge// system and print server; tests use small fakes.//// Each class is an interface: it says what can be asked, not how. `virtual`// lets a derived class supply the real behaviour, and `= 0` means this class// gives none, so you cannot create a plain BadgeDirectory, only a class// derived from it. The virtual destructor makes it safe to destroy a derived// object through a pointer to the interface.
// Asks the badge system who a badge belongs to. Returns the user's ID, or an// empty std::optional (std::nullopt) if the badge is unknown: an unknown// badge is an expected answer, not an error, so nothing is thrown.class BadgeDirectory {public: virtual ~BadgeDirectory() = default; [[nodiscard]] virtual std::optional<UserId> owner_of(const BadgeId& badge) const = 0;};
// Sends one job to one printer. The station calls this only for jobs that// have already been charged to the owner's quota.class PrintServer {public: virtual ~PrintServer() = default; virtual void print(const PrinterId& printer, const PrintJob& job) = 0;};VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// What happened when a badge was used: the jobs were looked at, the badge// was unknown, or the user had nothing waiting.enum class ReleaseOutcome { released, badge_not_recognised, no_jobs_waiting };// What happened to one job: printed, or left held because it did not fit.enum class JobOutcome { printed, over_quota };
// One job's outcome, named by its ID.struct JobResult { int job_id = 0; JobOutcome outcome = JobOutcome::printed;};
// Everything one badge-in produced. `jobs` is empty unless outcome is// released; then it has one entry per job the user had waiting.struct ReleaseResult { ReleaseOutcome outcome = ReleaseOutcome::released; std::vector<JobResult> jobs; // one per held job, oldest first};
// The text the printer's panel shows for one result (FR-4: say why).std::string panel_text(const ReleaseResult& result);
// Releases jobs at one printer. Owns nothing: the directory, held jobs,// quotas, and print server must outlive the station.// It holds references (&) to them, not copies, so every station in the// building shares the same held jobs and the same quotas. A reference must// be set when the object is built; it can never be made to refer to another// object, and it can never be null.class ReleaseStation {public: ReleaseStation(PrinterId printer, const BadgeDirectory& badges, HeldJobs& held, Quotas& quotas, PrintServer& server);
// Use case UC-2: the user at this printer has just badged in. Prints // each of their held jobs that fits their quota and reports every job. // An unknown badge or no waiting jobs is reported in the result, not // thrown. ReleaseResult release(const BadgeId& badge);
private: PrinterId printer_; // this station's own printer, a copy const BadgeDirectory& badges_; // const: the station only asks, never changes it HeldJobs& held_; Quotas& quotas_; PrintServer& server_;};ReleaseStation owns nothing. It holds references to the directory, the held
jobs, the quotas, and the print server, so they must all outlive it. The
results are values: an outcome for the whole release, and one result per job,
so the panel can say what happened and tests can check it.
VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// Use case UC-2: someone has badged in at this station's printer. Find out// who they are, then go through their held jobs, oldest first, printing// each one that fits their quota. Returns what happened to every job; never// throws for an unknown badge or an empty queue.ReleaseResult ReleaseStation::release(const BadgeId& badge) { // Ask the badge system who this is. An empty optional means "unknown // badge", and `!user` is true for an empty optional. const std::optional<UserId> user = badges_.owner_of(badge); // Early return: build a ReleaseResult from braces, outcome first and an // empty list of jobs (`{}`) second. Nothing has been printed or changed. if (!user) return {ReleaseOutcome::badge_not_recognised, {}};
// FR-8: only this user's jobs. FR-3: oldest first. // *user reads the UserId out of the optional; it is safe because the // check above has ruled out an empty one. `jobs` is a copy, so removing // printed jobs from held_ below cannot disturb this loop. const std::vector<PrintJob> jobs = held_.jobs_for(*user); if (jobs.empty()) return {ReleaseOutcome::no_jobs_waiting, {}};
// A reference to the user's account inside quotas_, so try_charge // below changes the real account, not a copy. QuotaAccount& quota = quotas_.account_for(*user); ReleaseResult result; // outcome starts as released, with no jobs yet for (const PrintJob& job : jobs) { // FR-4: each job is judged on its own. A job that does not fit is // not printed and stays held (assumption A5, Q20). // try_charge either takes all of the job's pages and returns true, // or takes none and returns false; it never charges part of a job. if (!quota.try_charge(pages_charged(job))) { result.jobs.push_back({job.id, JobOutcome::over_quota}); // `continue` skips the rest of this pass and goes on to the next // job, so a later, smaller job can still print. continue; } // Here the pages are already charged: print, then stop holding it. // remove's true/false answer is not needed: the job came from // held_ moments ago, so it is there. server_.print(printer_, job); held_.remove(job.id); result.jobs.push_back({job.id, JobOutcome::printed}); } return result;}How this code works: ReleaseStation::release
release answers three questions in order, and leaves as soon as one answer
means there is nothing to do.
- Who is this?
owner_ofreturns astd::optional<UserId>. If it is empty, the badge is unknown, and the function returns at once withbadge_not_recognisedand an empty list of jobs (flow 2a). No held job has been looked at, and nothing has changed. - What is waiting?
jobs_for(*user)returns a copy of the user’s held jobs, oldest first. If it is empty, the function returnsno_jobs_waiting(flow 3a). - What fits? The loop takes each job in turn and asks the user’s
account to
try_chargeits pages. The account either takes all of them and saystrue, or takes none and saysfalse.false: the job is recorded asover_quota, it stays held, andcontinuemoves straight on to the next job (flow 4a).true: the job is sent to the print server at this station’s printer, removed from the held jobs, and recorded asprinted.
- The result.
result.outcomewas never changed from its starting value,released, andresult.jobshas one entry per job, in the order they were looked at.
A worked example. In the demonstration, Kim has 20 pages left and badges in at 3-West with two held jobs. The jobs were the third and fourth held, so their IDs are 3 and 4.
| Job | Pages | try_charge |
Pages left after | Recorded as |
|---|---|---|---|---|
| 3, contract.pdf | 30 | false |
20 | over_quota, still held |
| 4, memo.docx | 5 | true |
15 | printed, removed |
panel_text counts one printed and one refused job, so the panel says
“Printing 1 job(s). 1 job(s) not printed: quota exceeded.” If the loop had
stopped at the first refusal instead of using continue, the memo would
not have printed, and AC-2.5 would fail.
Each step of the main flow is a line or two, and each alternate flow is an
early return or a continue. Two details are worth noticing:
jobs_forreturns a copy. The loop removes printed jobs fromheld_while it walks throughjobs. If it walked throughheld_’s own vector instead, each removal would shift the elements, and the loop would skip jobs or read past the end. Copying a user’s few jobs is cheap and removes the problem.- Charge, then print. If
printthrows, the pages are already charged but the job is still held. This example assumes printing succeeds; the invariants and failures lesson handles the failure, as flow 5a says.
Text description of the diagram
The printer’s badge read calls release on the release station with the badge. The station asks the badge directory who owns the badge and gets the user back. It asks the held jobs for that user’s jobs and gets them back, oldest first. Then, for each job, it asks the user’s quota account to charge the job’s pages and gets back whether they fit. If they fit, it tells the print server to print the job at this printer, and tells the held jobs to remove it. If they do not fit, the job is marked over quota and stays held. Finally the station returns the release result to the staff member. The two early refusals (unknown badge, no held jobs) are left out to keep the diagram small.
Diagram source (Mermaid)
sequenceDiagram
actor U as Staff member
participant S as ReleaseStation
participant B as BadgeDirectory
participant H as HeldJobs
participant Q as QuotaAccount
participant P as PrintServer
U->>S: release(badge)
S->>B: owner_of(badge)
B-->>S: user
S->>H: jobs_for(user)
H-->>S: jobs, oldest first
loop each job
S->>Q: try_charge(pages_charged(job))
Q-->>S: fits?
alt fits
S->>P: print(printer, job)
S->>H: remove(job.id)
else does not fit
Note over S: over_quota, job stays held
end
end
S-->>U: ReleaseResultThe diagram leaves out Quotas::account_for, a lookup inside the station’s
work, as the sequence-diagram lesson recommends for details inside one
participant.
Running it
Section titled “Running it”VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// The two outside systems. StaffBadges and ConsolePrintServer are small// stand-ins defined above main: B-01 is robin's badge, B-02 is kim's,// and "printing" writes a line to the console.const StaffBadges badges({{"B-01", "robin"}, {"B-02", "kim"}});ConsolePrintServer server;HeldJobs held;Quotas quotas(500); // every user starts each month with 500 pages// Kim has already printed 480 pages this month, leaving 20.// static_cast<void> says the true/false answer is ignored on purpose.static_cast<void>(quotas.account_for("kim").try_charge(480));
// Two printers in the building. Both stations refer to the same badges,// held jobs, quotas, and server, which are declared above them and so// outlive them.ReleaseStation east("2-East", badges, held, quotas, server);ReleaseStation west("3-West", badges, held, quotas, server);
// Times are minutes since midnight on day one: 09:00, 09:05, and so on.// hold returns the new job's ID, which this demo does not need.const minutes nine = hours{9};held.hold("robin", "budget.xlsx", 12, nine);held.hold("robin", "minutes.docx", 3, nine + minutes{5});held.hold("kim", "contract.pdf", 30, nine + minutes{10});held.hold("kim", "memo.docx", 5, nine + minutes{12});
// A small helper: badge in at a station and show what its panel says.// [] captures nothing; the station and badge come in as arguments.const auto badge_in = [](ReleaseStation& station, const BadgeId& badge) { const ReleaseResult result = station.release(badge); std::cout << badge << ": " << panel_text(result) << '\n';};
badge_in(east, "B-17"); // nobody owns B-17: nothing printsbadge_in(east, "B-01"); // robin: both jobs fit (12 + 3 of 500) and printbadge_in(east, "B-01"); // robin again: nothing is left to print// kim has 20 pages left: the 30-page contract is refused and stays held,// the 5-page memo prints, leaving 15.badge_in(west, "B-02");quotas.account_for("kim").grant_extra(20); // 15 + 20 = 35 pages leftbadge_in(west, "B-02"); // now the contract fits: 35 - 30 = 5 leftstd::cout << "robin has " << quotas.account_for("robin").remaining() << " pages left, kim has " << quotas.account_for("kim").remaining() << '\n';
// Expiry. A job held at 10:00 on day one reaches 24 hours at 10:00 on// day two (24 h + 10 h). One minute earlier it is kept; at 10:00 it goes.const minutes ten = hours{10};held.hold("kim", "draft.docx", 2, ten);const minutes next_day = hours{24};std::cout << "expired at 09:59 next day: " << held.expire(next_day + ten - minutes{1}) << '\n';std::cout << "expired at 10:00 next day: " << held.expire(next_day + ten) << '\n';std::cout << "held jobs: " << held.count() << '\n';B-17: Badge not recognised. [2-East] budget.xlsx, 12 pages, for robin [2-East] minutes.docx, 3 pages, for robinB-01: Printing 2 job(s).B-01: No jobs waiting. [3-West] memo.docx, 5 pages, for kimB-02: Printing 1 job(s). 1 job(s) not printed: quota exceeded. [3-West] contract.pdf, 30 pages, for kimB-02: Printing 1 job(s).robin has 485 pages left, kim has 5expired at 09:59 next day: 0expired at 10:00 next day: 1held jobs: 0The unknown badge prints nothing (flow 2a). Robin’s two jobs print oldest first; a second badge-in finds nothing (3a). Kim has 20 pages left: the contract does not fit, the memo does (4a). After facilities grants 20 pages, the contract prints, leaving Robin with 485 pages and Kim with 5. Finally, a job submitted at 10:00 is kept at 09:59 the next day and deleted at 10:00, leaving nothing held.
Tests named after criteria
Section titled “Tests named after criteria”VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// LLD_TEST(name) defines one test. LLD_CHECK(condition) records a failure// if the condition is false; LLD_CHECK_EQ(actual, expected) does the same// for `actual == expected` and prints both values when they differ; and// LLD_CHECK_THROWS(expression, type) fails unless the expression throws// that type of exception. A failed check does not stop the test: the// remaining checks still run. They come from the site's small test header,// lld_test.hpp.
// A fake badge system: the test fills `owners` with the badges it wants.// `override` asks the compiler to confirm this really replaces the virtual// function in BadgeDirectory. find returns an iterator to the matching// entry, or owners.end() if there is none; found->second is the user ID.class FakeBadges : public BadgeDirectory {public: std::map<BadgeId, UserId> owners; std::optional<UserId> owner_of(const BadgeId& badge) const override { const auto found = owners.find(badge); if (found == owners.end()) return std::nullopt; return found->second; }};
// Records what would have been printed, instead of printing it. A test// can then compare `printed` with the list it expects, in order.// emplace_back builds the (printer, job ID) pair straight in the vector.class RecordingPrintServer : public PrintServer {public: std::vector<std::pair<PrinterId, int>> printed; // printer, job ID void print(const PrinterId& printer, const PrintJob& job) override { printed.emplace_back(printer, job.id); }};
// Everything one test needs, built fresh by `Office office;` in each test,// so no test can see another's jobs or quotas.// Members are built in order, so the station is built last and refers to// the others; all are destroyed together at the end of each test.struct Office { FakeBadges badges; RecordingPrintServer server; HeldJobs held; Quotas quotas{500}; ReleaseStation station{"2-East", badges, held, quotas, server};
Office() { badges.owners = {{"B-01", "robin"}, {"B-02", "kim"}}; } // `station` refers to the other members, so a copy would refer to the // original's members. Office(const Office&) = delete; Office& operator=(const Office&) = delete; // Leaves `pages` of this month's quota for the user by charging the // rest of the 500: leave_quota("kim", 20) charges 480. The check fails // the test if that charge is refused. void leave_quota(const UserId& user, int pages) { LLD_CHECK(quotas.account_for(user).try_charge(500 - pages)); }};
const minutes nine = hours{9};
// AC-1.1 Given the print server reports a job, then it is held, nothing is// printed, and it is listed for its owner only.// Holds one job for robin, then proves the server printed nothing, robin's// list has exactly that job, and kim's list is empty. `1u` is an unsigned// 1, to match the unsigned type that size() returns.LLD_TEST(ac_1_1_a_reported_job_is_held_not_printed) { Office office; const int id = office.held.hold("robin", "budget.xlsx", 12, nine); LLD_CHECK(office.server.printed.empty()); const std::vector<PrintJob> robins = office.held.jobs_for("robin"); LLD_CHECK_EQ(robins.size(), 1u); LLD_CHECK_EQ(robins.front().id, id); LLD_CHECK(office.held.jobs_for("kim").empty());}
// AC-1.2 (protects assumption A8) A job with no pages is rejected.// Tries to hold a 0-page job: hold must throw std::invalid_argument, and// count() must still be 0, so the bad job was not stored.LLD_TEST(ac_1_2_a_job_with_no_pages_is_rejected) { Office office; LLD_CHECK_THROWS(office.held.hold("robin", "empty.pdf", 0, nine), std::invalid_argument); LLD_CHECK_EQ(office.held.count(), 0);}
// AC-2.1 Given a user with held jobs that fit their quota, when they badge// in, then every job prints at this printer, oldest first, their quota// goes down by the pages printed, and no job of theirs is still held.// Robin holds a 12-page and then a 3-page job. Comparing the whole// `printed` list proves both printed, at 2-East, in that order. 500 - 15 =// 485 pages are left, and nothing of robin's is still held.LLD_TEST(ac_2_1_badging_in_prints_all_held_jobs_oldest_first) { Office office; const int first = office.held.hold("robin", "budget.xlsx", 12, nine); const int second = office.held.hold("robin", "minutes.docx", 3, nine + minutes{5}); const ReleaseResult result = office.station.release("B-01"); LLD_CHECK(result.outcome == ReleaseOutcome::released); const std::vector<std::pair<PrinterId, int>> expected{{"2-East", first}, {"2-East", second}}; LLD_CHECK(office.server.printed == expected); LLD_CHECK_EQ(office.quotas.account_for("robin").remaining(), 485); LLD_CHECK(office.held.jobs_for("robin").empty());}
// AC-2.2 Given a badge the badge system does not know, when it is used,// then nothing prints and the panel says "Badge not recognised."// B-17 is not in the fake directory. The outcome and the panel text say// so, nothing printed, and robin's job is still held (count is 1).// hold's returned ID is not needed here, so it is simply not stored.LLD_TEST(ac_2_2_an_unknown_badge_prints_nothing) { Office office; office.held.hold("robin", "budget.xlsx", 12, nine); const ReleaseResult result = office.station.release("B-17"); LLD_CHECK(result.outcome == ReleaseOutcome::badge_not_recognised); LLD_CHECK_EQ(panel_text(result), std::string("Badge not recognised.")); LLD_CHECK(office.server.printed.empty()); LLD_CHECK_EQ(office.held.count(), 1);}
// AC-2.3 Given a user with no held jobs, when they badge in, then the panel// says "No jobs waiting."// Robin's badge is known but nothing is held for robin.LLD_TEST(ac_2_3_no_held_jobs_says_so) { Office office; const ReleaseResult result = office.station.release("B-01"); LLD_CHECK(result.outcome == ReleaseOutcome::no_jobs_waiting); LLD_CHECK_EQ(panel_text(result), std::string("No jobs waiting."));}
// AC-2.4 (assumption A5) Given a user with 20 pages of quota left, when they release a// 30-page job, then it is not printed, it stays held, the quota is// unchanged, and the panel says the quota is exceeded.// Kim has 20 pages left and holds a 30-page job. The checks prove each// part of the criterion: nothing printed, the job is still held, the// quota is still 20 (try_charge changed nothing), the result names the job// as over_quota, and the panel text gives the reason.LLD_TEST(ac_2_4_a_job_over_quota_is_not_printed_and_stays_held) { Office office; office.leave_quota("kim", 20); const int id = office.held.hold("kim", "contract.pdf", 30, nine); const ReleaseResult result = office.station.release("B-02"); LLD_CHECK(office.server.printed.empty()); LLD_CHECK_EQ(office.held.jobs_for("kim").size(), 1u); LLD_CHECK_EQ(office.quotas.account_for("kim").remaining(), 20); LLD_CHECK_EQ(result.jobs.size(), 1u); LLD_CHECK_EQ(result.jobs.front().job_id, id); LLD_CHECK(result.jobs.front().outcome == JobOutcome::over_quota); LLD_CHECK_EQ(panel_text(result), std::string("Printing 0 job(s). 1 job(s) not printed: quota exceeded."));}
// AC-2.5 (Q22) Given 20 pages left and held jobs of 30 then 5 pages, when the// user badges in, then the 5-page job prints and the 30-page job stays held.// The 30-page job comes first and does not fit; the loop goes on, so the// 5-page job still prints. Only `small` was printed, only `big` is still// held, and 20 - 5 = 15 pages are left.LLD_TEST(ac_2_5_each_job_is_judged_on_its_own) { Office office; office.leave_quota("kim", 20); const int big = office.held.hold("kim", "contract.pdf", 30, nine); const int small = office.held.hold("kim", "memo.docx", 5, nine + minutes{2}); static_cast<void>(office.station.release("B-02")); const std::vector<std::pair<PrinterId, int>> expected{{"2-East", small}}; LLD_CHECK(office.server.printed == expected); const std::vector<PrintJob> still_held = office.held.jobs_for("kim"); LLD_CHECK_EQ(still_held.size(), 1u); LLD_CHECK_EQ(still_held.front().id, big); LLD_CHECK_EQ(office.quotas.account_for("kim").remaining(), 15);}
// AC-2.6 Given two users with held jobs, when one badges in, then only that// user's jobs print.// Robin and kim both have a job held. After robin badges in, only robin's// job printed and kim's is still held.LLD_TEST(ac_2_6_only_the_badge_owners_jobs_print) { Office office; const int robins = office.held.hold("robin", "budget.xlsx", 12, nine); office.held.hold("kim", "contract.pdf", 30, nine); static_cast<void>(office.station.release("B-01")); const std::vector<std::pair<PrinterId, int>> expected{{"2-East", robins}}; LLD_CHECK(office.server.printed == expected); LLD_CHECK_EQ(office.held.jobs_for("kim").size(), 1u);}
// AC-2.7 (added by the traceability check for FR-2) Given a user's held// job, when they badge in at a different printer from the one in the other// tests, then it prints at that printer.// A second station, 3-West, shares the office's badges, held jobs,// quotas, and server. Badging in there prints robin's job at 3-West, which// proves the station sends jobs to its own printer, not a fixed one.LLD_TEST(ac_2_7_jobs_print_at_whichever_printer_the_user_badges_in_at) { Office office; const int job = office.held.hold("robin", "budget.xlsx", 12, nine); ReleaseStation west{"3-West", office.badges, office.held, office.quotas, office.server}; static_cast<void>(west.release("B-01")); const std::vector<std::pair<PrinterId, int>> expected{{"3-West", job}}; LLD_CHECK(office.server.printed == expected);}
// AC-3.1 Given a job held for 24 hours or more, when the expiry check runs,// then it is deleted and can no longer be released; a job held for less// than 24 hours is kept.// old.pdf was held at 09:00, new.pdf at 09:01. At 09:00 the next day,// old.pdf has waited exactly 24 hours, so it goes (the boundary case), and// new.pdf, one minute short, stays. Badging in then prints only one job.LLD_TEST(ac_3_1_jobs_held_24_hours_are_deleted) { Office office; office.held.hold("robin", "old.pdf", 4, nine); office.held.hold("robin", "new.pdf", 2, nine + minutes{1}); LLD_CHECK_EQ(office.held.expire(nine + hours{24}), 1); const std::vector<PrintJob> left = office.held.jobs_for("robin"); LLD_CHECK_EQ(left.size(), 1u); LLD_CHECK_EQ(left.front().document, std::string("new.pdf")); static_cast<void>(office.station.release("B-01")); LLD_CHECK_EQ(office.server.printed.size(), 1u);}
// AC-4.1 (assumption A5) Given a job refused for quota, when facilities grants enough extra// pages and the user badges in again, then the job prints.// Kim's 30-page job is refused with 20 pages left. 20 extra pages make// 40, so the second badge-in prints it, leaving 40 - 30 = 10. The printed// list has the job once: the first, refused attempt printed nothing.LLD_TEST(ac_4_1_extra_pages_let_a_refused_job_print) { Office office; office.leave_quota("kim", 20); const int id = office.held.hold("kim", "contract.pdf", 30, nine); static_cast<void>(office.station.release("B-02")); office.quotas.account_for("kim").grant_extra(20); static_cast<void>(office.station.release("B-02")); const std::vector<std::pair<PrinterId, int>> expected{{"2-East", id}}; LLD_CHECK(office.server.printed == expected); LLD_CHECK_EQ(office.quotas.account_for("kim").remaining(), 10);}
// AC-4.2 (assumption A6) Given extra pages granted this month, when a new// month starts, then the user has the normal monthly quota only.// Kim gets 50 extra pages and uses 40 (500 + 50 - 40 = 510 left). After// start_new_month, used and extra are both reset, so exactly the normal 500// is left: the 10 unused extra pages are gone.LLD_TEST(ac_4_2_extra_pages_do_not_carry_into_the_next_month) { Office office; QuotaAccount& kim = office.quotas.account_for("kim"); kim.grant_extra(50); LLD_CHECK(kim.try_charge(40)); kim.start_new_month(); LLD_CHECK_EQ(kim.remaining(), 500);}Each test’s name starts with its criterion’s ID, and its comment repeats the criterion. When a test fails, the report says which criterion is broken, in words a stakeholder would recognise. When a criterion changes, a search for its ID finds the test.
The tests use fakes for the two outside systems. FakeBadges is a map;
RecordingPrintServer records what would have been printed, so a test can
check the exact jobs, printers, and order. Because the station depends only
on the BadgeDirectory and PrintServer interfaces, it cannot tell the
difference. The Office fixture builds the four collaborators before the
station, because the station refers to them; members are built in the order
they are declared. For the same reason the fixture cannot be copied: a copy’s
station would still refer to the original’s members, which could be destroyed
first. Its copy operations are deleted, so the compiler refuses that mistake.
The traceability lesson builds a table from these IDs, from requirements to criteria to tests, and uses it to find what is not yet tested. (UC-5 and FR-6 are one gap already.)
When to use each tool
Section titled “When to use each tool”- Use cases pay off when an interaction has several alternate flows, more than one actor, or failures that need deciding, like UC-2.
- User stories suit planning small pieces of work and keeping the “why” visible. Their acceptance criteria do the precise work.
- Use-case diagrams help early, to check that every actor and every scope item is covered. They add little once the use cases are written.
- Given/When/Then criteria are almost always worth writing for behaviour that someone will test.
When not to
Section titled “When not to”- A full use case for a one-step interaction. UC-4 (grant extra pages) is one action and one result; its criteria are enough.
- Stories for technical work with no user. “As a developer, I want a storage interface” is not a user story; it is a design task. Say what it is.
- Criteria that repeat the code. “Then
try_chargereturns false” tests the implementation, not the behaviour. Describe what a user or another system would see.
Trade-offs
Section titled “Trade-offs”Use cases take longer to write than stories, and they can become long documents nobody reads. Stories are quick but easy to leave vague. Criteria with concrete values are precise, but there are many of them, and each one must be kept up to date. The balance this lesson suggests: a short list of use cases for the interactions with real alternatives, stories for planning, and concrete criteria for everything a test will check.
Common mistakes
Section titled “Common mistakes”- Only the main flow. The alternate flows are where the design decisions are.
- Use cases that describe the user interface (“click the blue button”) instead of the interaction. The interface will change; the goal will not.
- Criteria without concrete values, which leave the tester to invent them.
- Criteria that check only the happy result and not what must stay unchanged.
- Tests with no link to a criterion, so nobody knows which requirement breaks when they fail.
- Iterating over a container while removing from it, as the copy in
releaseavoids.
When a requirement changes
Section titled “When a requirement changes”New request: “Users should be able to choose which of their held jobs to release, instead of releasing all of them.”
- Use case: UC-2’s main flow gains a step between 3 and 4: the panel lists the user’s held jobs, and the user selects some. A new alternate flow covers the user selecting nothing.
- Criteria: new ones, such as “Given Robin holds jobs A and B, when Robin selects only B, then only B prints and A stays held.” AC-2.1 changes: “all held jobs print” becomes “all selected jobs print”.
- Code:
releasetakes the selected job IDs, or a second function does. The loop body (charge, print, remove) does not change. - Tests: AC-2.1’s test changes with its criterion; the rest still hold, because each one checks one flow.
The criteria IDs show exactly which tests are affected.
Exercise: Write acceptance criteria for a story
Here is a story for UC-5, which the example does not implement yet:
As the facilities manager, I want to set a user’s monthly quota, so that people whose work needs more printing are not blocked every month.
Write at least four acceptance criteria in Given/When/Then form, with concrete values. Include at least one criterion for an edge case. Note any question you would have to ask the facilities manager.
Show the explained answer
One reasonable set:
| ID | Given | When | Then |
|---|---|---|---|
| AC-5.1 | Sam has the default 500-page quota and has used 0 pages | facilities sets Sam’s quota to 800 | Sam has 800 pages left |
| AC-5.2 | Sam’s quota is 800, and Sam has used 300 pages this month | facilities sets it to 1,000 | Sam has 700 pages left this month |
| AC-5.3 | Sam’s quota is set to 800 | a new month starts | Sam has 800 pages, not the default 500 |
| AC-5.4 | Sam has used 300 pages this month | facilities sets Sam’s quota to 200 | Sam has 0 pages left this month, not a negative number; nothing already printed is undone |
| AC-5.5 | any user | facilities tries to set a quota of −10 pages | the change is refused, and the quota is unchanged |
How to judge your criteria:
- Edges. AC-5.4 (lowering a quota below what has been used) and AC-5.5 (an invalid value) are the cases most likely to be missing, and most likely to cause bugs. If you had only “set it and it is set”, add them.
- Persistence across months. AC-5.3 separates “this month’s quota” from “the user’s monthly quota”. The story’s “every month” says the change must last.
- Questions to ask. AC-5.4 hides a question: “If someone’s quota is cut below what they have already printed, what happens next month?” Also: “Does a new quota apply this month, or from next month?” AC-5.2 assumes this month; label that as an assumption until facilities confirms it.
- The story’s benefit. “So that people … are not blocked every month” supports AC-5.3 most directly. Criteria that serve the benefit are the most important ones.
Turning these into tests would also need a new operation on QuotaAccount,
such as set_monthly_pages(int). Notice that the criteria were written first,
in the domain’s words, before deciding that.
Summary
Section titled “Summary”- A use case describes one actor’s goal, with a main flow and alternate flows numbered by the step where they branch. Writing it puts several requirements together and surfaces questions.
- A use-case diagram is a table of contents: which actors take part in which use cases. Use it to check coverage.
- A user story names a role, a need, and a benefit. Its acceptance criteria make it precise.
- Given/When/Then criteria use concrete values, one event, observable results, and say what must not change.
- Each criterion becomes one test named after its ID; outside systems are replaced by fakes through small interfaces. Some requirements, such as response time, are checked by measurement instead.