Traces and sequence diagrams
What you will learn on this page
Section titled “What you will learn on this page”- How to write a trace: one scenario as numbered steps, each with the state it changes. It is the quickest way to check a design.
- When a trace is enough, and when a sequence diagram is clearer.
- What both show that a class outline or entity sketch cannot.
- The sequence-diagram notation: participants, messages, returns, and fragments for alternatives, options, and loops.
- How to draw a use case’s happy path and its failure paths, and how each arrow maps to a C++ call.
- What a sequence diagram reveals about a design: who talks to whom, in which order, and what happens when something fails half-way.
Two ways to show a scenario
Section titled “Two ways to show a scenario”An entity sketch and a class outline show which types exist, how they are connected, and what each one remembers and can do. They say nothing about what happens when someone uses the program. For that, you follow one scenario (one concrete use, with concrete values) through the objects, in order. There are two ways to write it down:
- A trace is a numbered list. Each step is one call, followed by what it returns or changes, after an arrow (→). It takes a minute to write, needs no tool, and is the quickest way to find a missing responsibility or a step in the wrong order. This site uses traces wherever a design is checked.
- A sequence diagram draws the same steps as arrows between the objects. It earns its place when three or more objects exchange messages, because then the picture shows at a glance who talks to whom, and when alternative paths (refusals, failures) need to be seen side by side.
Start with the trace. Draw the diagram when the trace becomes hard to follow.
In a sequence diagram:
- Each participant is an object (or a person, or an outside system), drawn as a box at the top with a vertical lifeline below it.
- Time runs downwards. A message drawn lower happens later.
- A message is a solid arrow from caller to callee. In C++ it is almost always a member function call.
- A return is a dashed arrow back, labelled with what comes back. It is optional: draw it when the value matters to the story.
That makes a sequence diagram the natural picture of one function that coordinates other objects, or of one use case from the user’s action to the result.
The example: a self-service checkout kiosk
Section titled “The example: a self-service checkout kiosk”A library has self-service kiosks. A member scans their library card and a book’s barcode. The kiosk checks that the card is registered, that the copy is on the shelf, and that the member is under their loan limit. Then it records the loan and prints a receipt with the due date.
VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// A library member as the kiosk needs them: an ID, a name for the receipt,// and how many books they may have out at once. A plain value: the// directory hands out copies of it.struct Member { std::string id; std::string name; int loan_limit = 0;};
// Knows: which library card belongs to which member.class MemberDirectory {public: // Registers a card. Adding a card that is already registered replaces // its member (insert_or_assign in kiosk.cpp). void add(std::string card, Member member); // Returns nothing if the card is not registered. // Otherwise returns a copy of the Member inside a std::optional, so the // caller never holds a pointer or reference into the directory. [[nodiscard]] std::optional<Member> find_by_card(const std::string& card) const;
private: std::map<std::string, Member> by_card_; // card number -> member};
// Knows: each copy's title, and whether it is on the shelf.class Catalog {public: // Adds a copy, on the shelf. A barcode already present is replaced. void add(std::string barcode, std::string title); // False for a barcode the catalog does not have. [[nodiscard]] bool is_on_shelf(const std::string& barcode) const; // Throw std::out_of_range for a barcode the catalog does not have. // title_of returns a reference to the title stored in the catalog, valid // until that copy is replaced or the catalog is destroyed. [[nodiscard]] const std::string& title_of(const std::string& barcode) const; void mark_lent(const std::string& barcode);
private: // Copy is private: only the catalog needs to know how a copy is stored. struct Copy { std::string title; bool on_shelf = true; }; std::map<std::string, Copy> copies_; // barcode -> copy};
// One open loan: which copy, which member, and the day it is due back.struct Loan { std::string barcode; std::string member_id; int due_day = 0;};
// Knows: the open loans.class LoanLedger {public: // Records a loan. It does not check for duplicates: the kiosk only // opens a loan for a copy that is on the shelf. void open(Loan loan); // How many open loans this member has (it looks at every loan). [[nodiscard]] int count_for(const std::string& member_id) const; [[nodiscard]] const std::vector<Loan>& loans() const noexcept { return loans_; }
private: std::vector<Loan> loans_;};
// What one receipt says: who borrowed what, and when it is due.struct Receipt { std::string member_name; std::string title; int due_day = 0;};
// Prints receipts while it has paper. Writes to a stream it does not own,// which must outlive the printer.class ReceiptPrinter {public: // out is where receipts are written (std::cout in main, a string stream // in the tests); sheets is how many receipts it can print before the // paper runs out. ReceiptPrinter(std::ostream& out, int sheets) noexcept : out_(out), sheets_(sheets) {} // Returns false, printing nothing, if the printer is out of paper. // Otherwise writes one line, uses one sheet, and returns true. bool print(const Receipt& receipt); [[nodiscard]] int printed() const noexcept { return printed_; }
private: std::ostream& out_; // a reference: the printer does not own the stream int sheets_; // sheets left int printed_ = 0; // receipts printed so far};Four collaborators, each knowing one thing, as in the responsibilities lesson: the member directory knows cards, the catalog knows copies, the ledger knows loans, and the printer prints.
VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// Every way one checkout can end. lent_without_receipt is a success: the// book is lent even though no receipt could be printed.enum class Outcome { lent, lent_without_receipt, unknown_card, not_on_shelf, at_loan_limit };
// A short English description of an outcome, for printing. std::string_view// is a read-only view of text; here it views a string literal, which lasts// for the whole program, so the view never dangles.[[nodiscard]] std::string_view describe(Outcome outcome) noexcept;
// Does: one checkout, by asking each collaborator in turn.class Kiosk {public: // Binds the kiosk to four collaborators that the caller owns, and sets // how long a loan lasts. The directory is const: the kiosk only reads it. Kiosk(const MemberDirectory& members, Catalog& catalog, LoanLedger& ledger, ReceiptPrinter& printer, int loan_days) noexcept : members_(members), catalog_(catalog), ledger_(ledger), printer_(printer), loan_days_(loan_days) {}
// One checkout of the copy `barcode` for the member with library card // `card`, on day `today`. Refusals change nothing. See kiosk.cpp. Outcome check_out(const std::string& card, const std::string& barcode, int today);
private: const MemberDirectory& members_; Catalog& catalog_; LoanLedger& ledger_; ReceiptPrinter& printer_; int loan_days_;};The kiosk owns none of its collaborators. It holds references to them, so they
must outlive it: main, and the tests’ Library, create the four
collaborators first and the kiosk last. find_by_card returns the Member by
value, in a std::optional, so the kiosk never holds a pointer into the
directory.
VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// The scenario the sequence diagram draws: three questions, then three// changes. Each refusal returns at once, before anything has changed.Outcome Kiosk::check_out(const std::string& card, const std::string& barcode, int today) { // A copy of the member, or an empty optional for an unknown card. const std::optional<Member> member = members_.find_by_card(card); if (!member) return Outcome::unknown_card; // empty optional: no such card // Also false for a barcode the catalog does not know. if (!catalog_.is_on_shelf(barcode)) return Outcome::not_on_shelf; // `member->id` reads a field of the Member inside the optional (safe: // the line above it returned if it was empty). `>=` because a member at // their limit, 2 loans of 2, may not take a third. if (ledger_.count_for(member->id) >= member->loan_limit) return Outcome::at_loan_limit;
// Every check has passed; now change things. The loan is recorded before // the receipt is printed, so a printer fault cannot lose a loan. const int due_day = today + loan_days_; ledger_.open({barcode, member->id, due_day}); catalog_.mark_lent(barcode); // The braces build a temporary Receipt (name, title, due day) for print. // title_of cannot throw here: is_on_shelf was true, so the copy exists. if (!printer_.print({member->name, catalog_.title_of(barcode), due_day})) { return Outcome::lent_without_receipt; } return Outcome::lent;}check_out is the scenario. Every call it makes on a collaborator is one
step in the trace, and one message in the diagram.
The happy path as a trace
Section titled “The happy path as a trace”Start with the scenario where everything goes right, with the values from the example program: Robin (card C-100, loan limit 2, no loans yet) checks out Dune (B-1) on day 10, and loans last 14 days.
- The member calls
kiosk.check_out("C-100", "B-1", 10). members_.find_by_card("C-100")→ Robin’sMember(ID M-1, limit 2).catalog_.is_on_shelf("B-1")→true.ledger_.count_for("M-1")→ 0. 0 is under the limit of 2, so every check has passed. Nothing has changed yet.ledger_.open({"B-1", "M-1", 24})→ the ledger now holds one open loan: B-1, M-1, due day 24.catalog_.mark_lent("B-1")→ B-1 is no longer on the shelf.catalog_.title_of("B-1")→"Dune".printer_.print({"Robin", "Dune", 24})→ printsReceipt: Robin | Dune | due day 24; returnstrue; the printer has no paper left.check_outreturnsOutcome::lent.
Writing the trace already shows the most important property of the design:
steps 2 to 4 only ask, and the first change is step 5. Follow a refusal (an
unknown card stops at step 2) and nothing has changed. Write the trace for the
fourth attempt in main, the second successful checkout, and step 8 returns false, after the loan is recorded, which
raises a question the code must answer (see “Alternatives and failures”).
Five objects take part, and three of the refusals branch off at different steps. That is where a picture helps.
The happy path as a sequence diagram
Section titled “The happy path as a sequence diagram”The same steps, drawn as messages. (The diagram shows a later checkout, when
the member already holds one loan, so count_for returns 1.)
Text description of the diagram
The member asks the kiosk to check out a book, giving the card, the barcode, and today’s date. The kiosk asks the member directory to find the card, and gets the member back. It asks the catalog whether the copy is on the shelf, and gets true. It asks the loan ledger how many loans the member has, and gets 1, which is under the limit. Then it tells the ledger to open the loan, tells the catalog to mark the copy as lent, asks the catalog for the title, and gets it back. It tells the receipt printer to print the receipt, and gets true. The kiosk returns “lent” to the member.
Diagram source (Mermaid)
sequenceDiagram
actor M as Member
participant K as Kiosk
participant D as MemberDirectory
participant C as Catalog
participant L as LoanLedger
participant P as ReceiptPrinter
M->>K: check_out(card, barcode, today)
K->>D: find_by_card(card)
D-->>K: member
K->>C: is_on_shelf(barcode)
C-->>K: true
K->>L: count_for(member.id)
L-->>K: 1
Note over K: 1 is under the limit
K->>L: open(loan)
K->>C: mark_lent(barcode)
K->>C: title_of(barcode)
C-->>K: title
K->>P: print(receipt)
P-->>K: true
K-->>M: lentRead the diagram from top to bottom, and compare it with the code:
- Each solid arrow after the first is one call made inside
check_out, in the same order. The first is the call tocheck_outitself. - Each dashed arrow is a return value that the kiosk uses to decide what
to do next, or, for the last one, reports to the member.
openandmark_lentreturn nothing worth drawing. - The member is an
actor, a person outside the program, drawn as a figure. Their “message” is the call that starts the scenario, which in a real kiosk would come from the user interface. - The note records a decision that happens inside the kiosk, without another object.
Not every C++ call becomes an arrow. std::optional’s operator bool,
std::map::find, and the Member copy are details inside one participant.
The diagram shows the conversation between objects, not every line of code.
Alternatives and failures
Section titled “Alternatives and failures”The happy path hides most of the design. A use case also has alternative paths: the card is unknown, the copy is out, the member is at the limit, the printer has no paper. A sequence diagram shows them with fragments, boxes drawn around part of the diagram:
| Fragment | Meaning | C++ |
|---|---|---|
alt / else |
exactly one of these paths happens | if / else if / else |
opt |
this part happens only if the condition holds | if with no else |
loop |
this part repeats | for, while |
par |
these parts happen at the same time | threads, tasks (later lessons) |
Each fragment is labelled with its condition in square brackets, called a
guard: [card not registered].
Text description of the diagram
The member asks the kiosk to check out a book. The kiosk asks the member directory for the card, and gets back an optional member. If the card is not registered, the kiosk returns “unknown card” to the member, and nothing else happens. Otherwise the kiosk asks the catalog whether the copy is on the shelf. If it is not, the kiosk returns “not on shelf”. Otherwise it asks the ledger how many loans the member holds. If the member is at the limit, the kiosk returns “at loan limit”. Otherwise, with every check passed, it opens the loan in the ledger, marks the copy as lent in the catalog, gets the title from the catalog, and asks the printer to print the receipt. If the printer is out of paper, the kiosk returns “lent without receipt”; if it printed, the kiosk returns “lent”.
Diagram source (Mermaid)
sequenceDiagram
actor M as Member
participant K as Kiosk
participant D as MemberDirectory
participant C as Catalog
participant L as LoanLedger
participant P as ReceiptPrinter
M->>K: check_out(card, barcode, today)
K->>D: find_by_card(card)
D-->>K: optional member
alt card not registered
K-->>M: unknown_card
else card found
K->>C: is_on_shelf(barcode)
C-->>K: on shelf?
alt not on shelf
K-->>M: not_on_shelf
else on shelf
K->>L: count_for(member.id)
L-->>K: loans held
alt at the loan limit
K-->>M: at_loan_limit
else under the limit
Note over K,C: every check passed, now change things
K->>L: open(loan)
K->>C: mark_lent(barcode)
K->>C: title_of(barcode)
C-->>K: title
K->>P: print(receipt)
P-->>K: printed?
alt out of paper
K-->>M: lent_without_receipt
else printed
K-->>M: lent
end
end
end
endWhat the diagram shows about the design
Section titled “What the diagram shows about the design”Drawing every path makes several design decisions visible, and some of them are easy to miss in the code:
- Checks before changes. All three refusals happen before the first
message that changes anything (
open). A refused checkout therefore leaves every object as it was, and the kiosk needs no code to undo anything. If the diagram showedmark_lentabovecount_for, the refusal at the limit would leave a copy marked as lent with no loan, and the diagram would make that plain. - A failure after the change. The printer can fail after the loan is
recorded. The design must decide what that means. Here, the loan stands, and
the member is told there is no receipt: losing the receipt is better than
losing the record of who has the book. The other choice, undoing the loan
when printing fails, would add two more messages (
closeandmark_returned), and would have to cope with them failing too. Whichever is chosen, the diagram is where it becomes a decision instead of an accident. Only the printer running out of paper is modelled here. An exception afteropen(building the receipt’s strings could run out of memory) would also leave the loan standing, with the exception reaching the caller. - One coordinator. Every arrow starts or ends at the kiosk. The collaborators never call each other, which is the low coupling that the lesson on drawing class designs pointed out in the loan desk. A sequence diagram where messages pass along a chain (A asks B, which asks C, which asks D) suggests that A depends on things it cannot see.
- The cost of each step. Every message is a call; in a distributed system, each one might be a network round trip. Here they are all cheap, local calls, but the diagram is where to count them.
Running it
Section titled “Running it”VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
MemberDirectory members;// Card C-100 belongs to Robin, member M-1, who may hold 2 books at once.members.add("C-100", Member{"M-1", "Robin", 2});
Catalog catalog;catalog.add("B-1", "Dune");catalog.add("B-2", "Emma");catalog.add("B-3", "Ulysses");
LoanLedger ledger;ReceiptPrinter printer(std::cout, 1); // one sheet of paper leftKiosk kiosk(members, catalog, ledger, printer, 14); // 14-day loans, created last
// A small helper (a lambda) for one attempt on day 10: it checks out// and prints the outcome. [&] lets it use `kiosk` from main by// reference, without copying it.auto attempt = [&](const std::string& card, const std::string& barcode) { const Outcome outcome = kiosk.check_out(card, barcode, 10); // may print a receipt std::cout << card << ' ' << barcode << ": " << describe(outcome) << '\n';};attempt("C-100", "B-1"); // prints the receipt first, then "lent"attempt("C-999", "B-2"); // no member has card C-999attempt("C-100", "B-1"); // B-1 was lent by the first attemptattempt("C-100", "B-2"); // no paper leftattempt("C-100", "B-3"); // Robin already has 2 loansstd::cout << "open loans: " << ledger.loans().size() << '\n'; // B-1 and B-2Receipt: Robin | Dune | due day 24C-100 B-1: lentC-999 B-2: refused: unknown cardC-100 B-1: refused: copy not on the shelfC-100 B-2: lent, but no receipt (printer out of paper)C-100 B-3: refused: loan limit reachedopen loans: 2The printer starts with one sheet, so the first checkout prints a receipt (the
receipt line comes before “lent”, because print runs inside check_out). The
second checkout tries an unknown card, and the third asks for the copy that is
now out. The fourth is lent, but the printer has no paper left. Robin’s limit
is 2, so the fifth is refused at the limit. Each line follows one path through
the diagram.
Testing each path
Section titled “Testing each path”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, and LLD_CHECK_EQ(actual, expected) records a// failure unless the two are equal, printing both. They come from the// site's small test header, lld_test.hpp.
// namespace { ... } with no name keeps the helper private to this file.namespace {
// Everything a kiosk talks to, created before the kiosk and outliving it.// Members of a class are created in the order they are declared, and// destroyed in the reverse order. So `paper` exists before the printer// that writes to it, and all four collaborators exist before `kiosk`, which// is destroyed first. Each test builds its own Library, so tests share// nothing.struct Library { MemberDirectory members; Catalog catalog; LoanLedger ledger; std::ostringstream paper; // collects the printed receipts as text ReceiptPrinter printer; Kiosk kiosk;
// sheets: how much paper the printer starts with. Loans last 14 days. // Sam (card C-1, member M-1) may hold only 1 book. explicit Library(int sheets) : printer(paper, sheets), kiosk(members, catalog, ledger, printer, 14) { members.add("C-1", Member{"M-1", "Sam", 1}); catalog.add("B-1", "Dune"); catalog.add("B-2", "Emma"); }};
} // namespace
// Every message has its effect: one loan, due on day 10 + 14 = 24; B-1 off// the shelf; and exactly the expected receipt on the "paper".LLD_TEST(happy_path_records_the_loan_then_prints) { Library library(5); LLD_CHECK(library.kiosk.check_out("C-1", "B-1", 10) == Outcome::lent); LLD_CHECK_EQ(library.ledger.count_for("M-1"), 1); LLD_CHECK_EQ(library.ledger.loans().at(0).due_day, 24); LLD_CHECK(!library.catalog.is_on_shelf("B-1")); LLD_CHECK_EQ(library.paper.str(), std::string("Receipt: Sam | Dune | due day 24\n"));}
// An unknown card stops at the first question: the copy stays on the// shelf, no loan is opened, and nothing is printed.LLD_TEST(unknown_card_stops_before_any_other_message) { Library library(5); LLD_CHECK(library.kiosk.check_out("C-404", "B-1", 10) == Outcome::unknown_card); LLD_CHECK(library.catalog.is_on_shelf("B-1")); LLD_CHECK(library.ledger.loans().empty()); LLD_CHECK_EQ(library.printer.printed(), 0);}
// A second member, Kim, borrows B-1 first. Sam's request for B-1 (now out)// and for B-9 (not in the catalog) are both refused as not_on_shelf, and// leave only Kim's loan and Kim's one receipt.LLD_TEST(copy_not_on_shelf_changes_nothing) { Library library(5); library.members.add("C-2", Member{"M-2", "Kim", 3}); LLD_CHECK(library.kiosk.check_out("C-2", "B-1", 10) == Outcome::lent); LLD_CHECK(library.kiosk.check_out("C-1", "B-1", 11) == Outcome::not_on_shelf); LLD_CHECK(library.kiosk.check_out("C-1", "B-9", 11) == Outcome::not_on_shelf); // unknown LLD_CHECK_EQ(library.ledger.loans().size(), std::size_t{1}); LLD_CHECK_EQ(library.ledger.count_for("M-1"), 0); LLD_CHECK_EQ(library.printer.printed(), 1);}
// Sam's limit is 1: the first book is lent, the second refused. B-2 stays// on the shelf, and only the first receipt was printed.LLD_TEST(loan_limit_changes_nothing) { Library library(5); LLD_CHECK(library.kiosk.check_out("C-1", "B-1", 10) == Outcome::lent); LLD_CHECK(library.kiosk.check_out("C-1", "B-2", 10) == Outcome::at_loan_limit); LLD_CHECK(library.catalog.is_on_shelf("B-2")); LLD_CHECK_EQ(library.ledger.count_for("M-1"), 1); LLD_CHECK_EQ(library.printer.printed(), 1);}
// No paper at all. The loan and the shelf change still happen, because they// come before printing; only the receipt is missing.LLD_TEST(printer_fault_after_the_loan_keeps_the_loan) { Library library(0); LLD_CHECK(library.kiosk.check_out("C-1", "B-1", 10) == Outcome::lent_without_receipt); LLD_CHECK_EQ(library.ledger.count_for("M-1"), 1); LLD_CHECK(!library.catalog.is_on_shelf("B-1")); LLD_CHECK(library.paper.str().empty());}A sequence diagram with alternatives is a list of tests: one test per path. Each test checks the return value and which messages had an effect:
- The happy path: a loan is opened with the right due day, the copy is no longer on the shelf, and the receipt says what it should.
- Each refusal: nothing changed. The loan list is empty, or unchanged, and
no receipt was printed. That checks “checks before changes”. The
not-on-shelf test tries both a copy that is out and a barcode the catalog
does not have:
is_on_shelfreturns false for both, so both take the same path. - The failure after the change: the loan stands although the printer failed.
The tests see the messages through their effects on real objects. A test can also replace a collaborator with a fake that records every call it receives, and then check the order of calls exactly. That needs the kiosk to depend on interfaces rather than concrete classes, which the principles and testing sections cover.
Choosing what to draw
Section titled “Choosing what to draw”- One scenario, or one use case with its alternatives, per diagram. The happy path alone is a good first drawing. Add the alternatives when the failures are the point, as they usually are in review.
- Draw objects, not classes. A participant is an object taking part in
this scenario. If two objects of the same class take part, they are two
participants (
source : Accountandtarget : Account). - Leave out the details inside one participant: standard library calls, getters on values, logging.
- Label messages with the operation and its important arguments, so that each arrow can be found in the code, and returns with what comes back.
- Nesting gets deep. Four nested
alts, as above, is already at the limit of readability. A function whose diagram nests deeper may be doing too much, or each failure path may deserve its own small diagram.
Traces and sequence diagrams are also useful before the code exists. Write the use case as a trace, using the classes from the entity sketch. Each step that arrives at an object is a member function that class needs; add it to the class outline. If a step has no obvious receiver, a responsibility has no owner yet. That is how a trace and a class outline check each other, and it is how steps 3 and 4 of the delivery framework work together.
Common mistakes
Section titled “Common mistakes”- Only the happy path. The design questions are in the alternatives.
- Every line of code as a message. The diagram becomes a slower way to read the function.
- Messages that do not exist in the code, or a different order from the code. A diagram that disagrees with the code teaches the wrong design.
- A diagram with no starting message. Every scenario starts with something: a user action, a timer, a message from another system. Draw it.
- Confusing the two arrows. A solid arrow is a call; a dashed arrow is a return. A dashed arrow from the caller to the callee means nothing.
When a requirement changes
Section titled “When a requirement changes”New requirement: “Members who have given an e-mail address get their receipt by e-mail instead of on paper.”
On the diagram, the change is one alt fragment around the last step: if the
member has an e-mail address, the kiosk sends the receipt to a new participant,
EmailSender; otherwise it prints as before. Drawing it raises the questions
the code must answer. What if sending fails, is it the same as running out of
paper? Should the kiosk wait for the e-mail to be sent, or hand it to a queue
and return at once? The second answer changes the diagram more: the kiosk’s
message to the sender becomes an asynchronous message (drawn with an open
arrowhead, -) in Mermaid, meaning the caller does not wait), and sending happens later, after the
member has gone.
Exercise: Draw the sequence for a given function
The responsibilities lesson’s loan desk has this checkout:
VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// Asks first, changes last. The three checks only read; each one that fails// returns its reason at once, so later lines run only if every earlier// check passed, and a refused checkout changes nothing.CheckoutResult LoanDesk::check_out(const MemberAccount& member, const std::string& copy_id, int today) { if (!catalog_.owns(copy_id)) return CheckoutResult::no_such_copy; if (!catalog_.is_on_shelf(copy_id)) return CheckoutResult::not_on_shelf; // The ledger knows how many loans the member has now; "+ 1" counts the // copy being borrowed, and the account decides if that many is allowed. if (!member.may_hold(ledger_.count_for(member.id()) + 1)) { return CheckoutResult::member_may_not_borrow; } // A copy is on the shelf exactly when it has no open loan, so open() // succeeds here. If it throws (out of memory), nothing has changed yet. // {copy_id, member.id(), today + loan_days_} builds a Loan in field // order; the due day is today plus the loan period. ledger_.open({copy_id, member.id(), today + loan_days_}); // Cannot throw: owns(copy_id) was checked above. catalog_.mark_lent(copy_id); return CheckoutResult::lent;}
// The ledger decides whether the copy was out. close() returns an empty// optional if it was not, and `!` on an empty optional is true, so the// function returns false and changes nothing. The closed Loan itself is not// needed here, so the returned optional is destroyed straight away.bool LoanDesk::check_in(const std::string& copy_id) { if (!ledger_.close(copy_id)) return false; catalog_.mark_returned(copy_id); return true;}- Write the happy path as a numbered trace, for a member with limit 3 and one loan, checking out a copy that is on the shelf on day 5, with 21-day loans.
- Draw the sequence diagram for
LoanDesk::check_out, with every path. The member account is passed in as a parameter. - If the order of
openandmark_lentwere swapped, would any path change?
Show the explained answer
1. The trace. Say the member is M-7 and the copy is C-12; the desk was built with 21-day loans.
- The caller calls
desk.check_out(member, "C-12", 5). catalog_.owns("C-12")→true.catalog_.is_on_shelf("C-12")→true.ledger_.count_for("M-7")→ 1.member.may_hold(2)→true(2 is within the limit of 3, and the member is not blocked). Every check has passed; nothing has changed yet.ledger_.open({"C-12", "M-7", 26})→ the ledger now holds the loan, due day 26.catalog_.mark_lent("C-12")→ C-12 is no longer on the shelf.check_outreturnsCheckoutResult::lent.
Step 5 asks “may the member hold one more?”, so the argument is the
current count plus one. A trace with real numbers makes that + 1 easy to
check; reading the code alone, it is easy to miss.
2. The diagram.
Text description of the diagram
The caller asks the loan desk to check out a copy for a member. The desk asks the catalog whether it owns the copy. If not, it returns “no such copy”. Otherwise it asks the catalog whether the copy is on the shelf; if not, it returns “not on shelf”. Otherwise it asks the ledger how many loans the member holds, then asks the member account whether the member may hold one more. If not, it returns “member may not borrow”. Otherwise it opens the loan in the ledger, marks the copy as lent in the catalog, and returns “lent”.
Diagram source (Mermaid)
sequenceDiagram
participant caller
participant D as LoanDesk
participant C as Catalog
participant A as MemberAccount
participant L as LoanLedger
caller->>D: check_out(member, copy_id, today)
D->>C: owns(copy_id)
C-->>D: owned?
alt copy not owned
D-->>caller: no_such_copy
else owned
D->>C: is_on_shelf(copy_id)
C-->>D: on shelf?
alt not on shelf
D-->>caller: not_on_shelf
else on shelf
D->>L: count_for(member.id())
L-->>D: loans held
D->>A: may_hold(loans held + 1)
A-->>D: allowed?
alt not allowed
D-->>caller: member_may_not_borrow
else allowed
D->>L: open(loan)
D->>C: mark_lent(copy_id)
D-->>caller: lent
end
end
endPoints to check in your drawing:
- The caller is not an actor here: the desk is called by other code. Any name for it is fine.
member.id()is a getter on the account. You may draw it as a message to the account, or leave it out as a detail; either is reasonable. The call tomay_holdis a decision the account makes, so it should be drawn.open’s return value is not drawn, because the code does not use it.
3. Swapping open and mark_lent changes no path: both happen after every
check, so a refusal still changes nothing. It does change one failure that the
diagram does not show. open can throw if memory runs out. In the code’s order,
nothing has changed when it throws. In the swapped order, the copy would already
be marked as lent with no loan recorded. The code’s comment says exactly this.
A diagram can show an exception as an alt or a note, but most leave it out;
this is a case where it would have earned its place.
Summary
Section titled “Summary”- A trace shows one scenario as numbered steps, each with what it returns or changes. Write one whenever you check a design; it is the fastest way to find a missing responsibility or a change made before a check.
- A sequence diagram shows one scenario: participants, and the messages between them, in time order from top to bottom.
- A solid arrow is a call; a dashed arrow is a return.
alt,opt, andloopfragments showif/else,if, and loops, each with a guard. - Draw the happy path first, then the alternatives. The alternatives show the design: checks before changes, what happens after a failure half-way, and who talks to whom.
- Each path through the diagram is a test.
- Draw a sequence diagram when several objects take part and the order or the failures matter; leave the details inside each participant out.