Skip to content
  • How to take a working design one step further on your own: from a changed requirement, through questions and acceptance criteria, to a change whose size you can justify.
  • How to judge your own solution when there is no single right answer, using criteria instead of a model answer.
  • How each study’s own limitations point at the next realistic change, and why the study’s design makes some of those changes cheap and others expensive.

Each challenge below belongs to one case study. Attempt it after you have read that study, including its change and its production limitations, because every challenge starts from the study’s finished code and builds on something the study says it left out.

For each challenge:

  1. Read the changed requirement and settle the questions first. Real changes arrive vague. Write down your answer to each question, and mark each one as an assumption if nobody could confirm it; see Assumptions versus confirmed requirements.
  2. Write the requirements and the acceptance criteria before any code. Give them IDs that continue the study’s numbering (the next FR, the next UC), so that a test name can point at a criterion.
  3. Start from the step the challenge names, and keep its tests green. The study’s existing tests are your safety net. If one of them must change, that is a change of requirement: say which one and why, as the studies do in their “What moved” sections. See Design evolution.
  4. Write the first new test before the new code. The hints say which test is a good first one.
  5. Open the hints only when you are stuck, and the evaluation criteria only when you have a solution, or a design you would defend.

There is more than one good design for every challenge. The evaluation criteria name at least two acceptable designs and what each costs, but they are criteria, not a model answer: a design that is not listed can be just as good if it meets the criteria and you can say why you chose it. Each challenge is sized for a few hours of work, including the tests.

The criteria in each challenge add to this list; they do not repeat it.

  • The study’s existing acceptance tests still pass, unchanged, or each changed test is traced to a requirement that changed.
  • The new acceptance criteria are tested, including the refusals and the boundaries (the exact limit, the moment of expiry, the empty case).
  • Ownership and lifetimes are stated for every new member and every new reference or pointer: who owns it, who only observes it, and what guarantees that it outlives its users.
  • Concurrency safety is stated where the study has threads: which lock protects the new data, and what is never done while holding it. Where the study is single-threaded, the solution says it still is.
  • The change is local, or its spread is justified. A good solution can list the files and types it touched, and explain each one by a requirement.
  • The design matches the requirements you wrote, not more. A pattern or an interface that no requirement needs is a cost, not a credit.

The challenges follow the order of the curriculum. Each names the study’s own words for the limitation it builds on, with a link, so you can read the study’s reasoning first.

Builds on: the Scope, which puts lost tickets out of scope, and the Production limitations, which repeat that “lost tickets, reservations, passes, and licence-plate cameras were out of scope, and each would add requirements and classes”.

The changed requirement.

“Drivers lose tickets every week, and the attendant has to let them out by hand. A driver who has lost their ticket should pay a lost-ticket charge of 25.00 at the pay station, after the attendant confirms which spot the car is in. If the old ticket turns up later, it must not open the gate.”

Starting point. Step 4 of the parking lot study, the last of its four steps (floors and electric-vehicle chargers are already in it), in examples/case-studies/parking-lot/step-4/.

Questions to settle first.

  1. Is the charge exactly 25.00, or the larger of 25.00 and the fee the stay has run up so far? What stops a driver from “losing” a ticket to pay less?
  2. Does a lost-ticket stay at a charger spot still pay for charging, and does the receipt still show parking and charging separately?
  3. What should happen if the ticket was already paid and then lost before the driver reached the gate?
  4. Who may use this path? The study notes that the operator is not authenticated; is that acceptable for an attendant action?
Show the hints
  • Types and invariants affected: Ticket and its TicketState (active, paid, exited), and the rule that a spot is occupied exactly while its ticket has not exited. A lost ticket is still the same stay; it is not a new ticket.
  • Finding the ticket: each spot already records the ticket parked on it, so “which ticket belongs to this spot?” may need no new index. Check that before you add one, for the reason the study gives against a second copy of the truth.
  • Where the change lives: in ParkingLot, next to pay and exit, because it ends a stay. The fee rules (FeeRule) price a stay; the lost-ticket charge is a policy about missing evidence, so think carefully before making it a fee rule.
  • First test: a car enters, the attendant reports its ticket lost by spot, the driver pays, and the gate opens; then the original ticket number is refused at the exit, and the spot is free exactly once.
Show the evaluation criteria

A good solution shows:

  • A test that the old ticket, if found, is refused at the pay station and at the exit, with a reason a driver can be shown.
  • A test at the boundary of your answer to question 1 (for example, a stay whose fee is exactly 25.00, and one just above it).
  • That the spot is freed once and only once, and the free-spot board stays right.
  • That no new ticket was created for the same car, or, if one was, an explanation of how the old one is closed and why two tickets for one stay are worth it.

Acceptable designs include:

  • A new operation on ParkingLot that takes a spot, finds its active ticket, and settles it with the lost-ticket charge, reusing the existing payment and exit steps. Small and local; the cost is that the lot now has a second way to end a stay, which the tests must cover as fully as the first.
  • A “lost” mark on the ticket (a new state, or a flag the state machine checks) that changes what amount_due returns, followed by the ordinary pay and exit. It reuses more of the existing path; the cost is a fourth state or a flag that every switch on TicketState must now consider.

Common mistakes: making losing a ticket cheaper than keeping it; issuing a replacement ticket and leaving the old one active, so the spot looks occupied for ever; and treating the lost-ticket charge as a FeeRule, which breaks the rule’s contract that the price depends on the stay.

CS-02 Vending machine: coin tubes that fill up

Section titled “CS-02 Vending machine: coin tubes that fill up”

Builds on: the Scope, which assumes that “the coin box holds as many coins as it is given”, and the Production limitations: real machines keep change in tubes of fixed size and send extra coins to a cash box that cannot pay change, so the model “never needs to say ‘exact change only’”.

The changed requirement.

“Our machines have one tube per coin, and each tube holds 50 coins. Once a tube is full, more of that coin drop into the cash box, and the machine cannot use those for change. When it might not be able to give change, the display should say EXACT CHANGE ONLY.”

Starting point. Step 2 of the vending machine study (card payment included), in examples/case-studies/vending-machine/step-2/.

Questions to settle first.

  1. When exactly is EXACT CHANGE ONLY shown? Pick a rule you can state in one sentence and test, such as “some tube is below a level”, or “the tubes cannot make change for the largest overpayment on the cheapest product”.
  2. Is a sale still refused when change cannot be made, as today, or does the warning change that?
  3. When the door is open, can the operator load more coins than a tube holds? Is emptying the cash box a new maintenance action?
  4. The customer’s inserted coins are kept apart until the sale. On cancel, they come back as today; does anything change there?
Show the hints
  • Types and invariants affected: the machine’s coin box, a Coins value today. New invariants: no tube holds more than its capacity, and coins in the cash box are never paid out as change.
  • make_change stays a free function. It needs an amount and some coins. Give it the tubes only, and it does not need to change at all.
  • Where the change lives: where the customer’s coins are added to the box at the end of a sale, and in the maintenance actions. The card sale (step 2) takes no coins, so it should need no change.
  • First test: a box whose tubes are nearly full, and a sale that would need a coin that went to the cash box to make change. The sale must be refused, or handled by your answer to question 2, and the display checked.
Show the evaluation criteria

A good solution shows:

  • A test that a tube never goes over its capacity, at the exact capacity and one coin over.
  • A test that a sale whose change exists only if cash-box coins were counted does not pay out those coins.
  • A test for the EXACT CHANGE ONLY rule you wrote, both when it shows and when it does not, in each state the display can be read in.
  • That the machine is still one customer at a time on one thread, as the study says.

Acceptable designs include:

  • A small CoinStore class that owns the tubes, their capacities, and the cash box, with operations such as “accept these coins” and “pay this change”. The rules about capacity live in one place and are tested alone; the cost is one more class, which the study avoided for slots because it “would mostly forward calls”. Here it would hold a real rule.
  • Two members in the machine, the tubes as Coins with a capacity array, and the cash box as a total. Fewer types; the cost is that the capacity rule lives in the machine’s sale and maintenance code, in more than one place.

Common mistakes: letting make_change see the cash box; checking the capacity after the coins have already moved, so a failure leaves the box half updated; and showing the warning without making the sale path respect the same rule.

CS-03 Library management: lost and withdrawn copies

Section titled “CS-03 Library management: lost and withdrawn copies”

Builds on: the Production limitations: “No lost, damaged, or withdrawn copies. A fourth status would be needed, and the fine rules for a lost book.” The Scope also lists lost and damaged copies as out of scope.

The changed requirement.

“When a member tells us they have lost a book, we charge them for a replacement and take the copy off the catalogue. We also withdraw damaged copies from the shelf. Neither kind of copy should ever be offered to someone waiting in the hold queue.”

Starting point. Step 2 of the library management study (the hold queue included), in examples/case-studies/library-management/step-2/.

Questions to settle first.

  1. What does a member owe for a lost copy: a fixed replacement fee, the fine so far, both, and is the fine cap still applied?
  2. Can a lost copy be found and returned? If so, is anything refunded?
  3. Does a lost copy still count against the member’s loan limit?
  4. A copy on the hold shelf is found damaged. What happens to the member it was set aside for: do they keep their place, or move to the front for the next copy?
Show the hints
  • Types affected: CopyStatus is std::variant<OnShelf, OnLoan, OnHoldShelf>. A new alternative (or two) is the natural place for “lost” and “withdrawn”. Every std::visit and every check on the status must then say what it does with the new alternative, and the compiler can point at the visits that miss it.
  • Money: a member’s debt never goes below zero, and the fine numbers live in Policy. A replacement fee is one more number there, not a new class.
  • Where the change lives: Copy (its allowed moves), Library (the new operations and the fee), and the hold logic that chooses the next copy for a waiting member.
  • First test: a copy on loan is reported lost; the member owes the fee; a member waiting for the title is not given that copy, and is given the next copy that comes back.
Show the evaluation criteria

A good solution shows:

  • That a lost or withdrawn copy can never move back to the shelf or the hold shelf by any path, unless your requirements allow “found”, in which case that move is tested.
  • A test of the hold queue when the copy set aside is withdrawn: the next copy, and the next member, follow the order you chose in question 4.
  • That the existing fine rules and their tests are unchanged.

Acceptable designs include:

  • Two new alternatives, such as Lost (with the member and the date) and Withdrawn. Each says exactly what it means; the cost is two more cases in every visit.
  • One alternative, Removed, with a reason. Fewer cases; the cost is that rules that differ by reason (only a lost copy has a member who pays) end up as checks inside one case.
  • Removing the copy from the repository and recording the charge on the member. The fewest status cases; the cost is that the library forgets the copy existed, which matters if a lost copy can be found, and the study already notes that there is no history to settle disputes.

Common mistakes: a bool lost next to the status, which the study argues against in The copy’s status: flags or one value; charging the fee without a test of the cap you chose; and forgetting that the hold logic must skip removed copies.

CS-04 Logging framework: levels by name prefix

Section titled “CS-04 Logging framework: levels by name prefix”

Builds on: the Scope, which puts hierarchical logger names out of scope (“a level for http that also applies to http.client”), and What is not here, and why: “The team did not ask for it; it would replace the map lookup with a walk up the name.”

The changed requirement.

“We have forty loggers under http. and we want to turn all of them to debug while we chase a bug, without listing each one. A level set on http should apply to every logger whose name starts with http., unless that logger has a level of its own.”

Starting point. Step 2 of the logging framework study (fields, JSON lines, and the rotating file included), in examples/case-studies/logging-framework/step-2/.

Questions to settle first.

  1. When the level of http changes, must loggers under it change at once, even ones that threads are using right now?
  2. Is a level set on a name that has no logger yet remembered, so that a logger made later under it picks it up?
  3. How does a logger with its own level go back to following its parent?
  4. Does http also cover https? (It should not; say how your design makes sure.)
Show the hints
  • Types and invariants affected: a Logger’s level is a std::atomic<Level>, read with one relaxed load on every call (NFR-2), and the loggers live in a std::map owned by LogSystem, so a Logger& stays valid. Keep both properties.
  • Where the walk happens: the study’s note names the cost of walking up the name on every call. You can instead do the work when a level is set: under the lock LogSystem already takes for logger(), work out each affected logger’s effective level and store it in its atomic. Log calls then still do one load.
  • A sorted map helps. The names under http. are next to each other in a std::map ordered by name, so they are one range. Search for the prefix with the dot, not for http alone, or https will match.
  • First test: set http to warn; a debug line on http.client is dropped, and a warning is kept; then give http.client its own level of debug, and its debug lines appear while http.server’s do not.
Show the evaluation criteria

A good solution shows:

  • That a call below the level still costs one atomic load and no string work (inspect the code path, since NFR-2 is a property of the code, not a benchmark).
  • A test with threads that log while another thread changes a parent’s level, run under the tsan preset, and a statement of what a thread may see during the change (old level or new level, never anything else).
  • Tests for your answers to questions 2 and 3, and for the https case.
  • That routes and sinks are untouched: they are const after construction, and this change has no reason to alter that.

Acceptable designs include:

  • Each logger stores its own optional explicit level and its effective level; setting a level recomputes the effective levels of the range below it, under the lock. Log calls stay as fast as today; the cost is that setting a level is no longer constant time, which is fine for an operator action.
  • A separate table of levels by prefix, consulted when a logger is made and whenever the table changes, again writing each logger’s atomic. It remembers levels for names with no logger yet (question 2); the cost is a second structure that must agree with the loggers.

Common mistakes: walking the dotted name on every log call; matching the prefix without the dot; forgetting loggers created after the level was set; and taking a lock on the log path.

CS-05 Cache with eviction policies: a limit in bytes

Section titled “CS-05 Cache with eviction policies: a limit in bytes”

Builds on: What is not here, and why: “No limit in bytes … A byte limit would need a size function for V, and a put that can evict several entries.” The Production limitations add that, with capacity in entries, “a cache of large and small values cannot promise a memory limit”.

The changed requirement.

“We now cache thumbnails and full images in the same cache. Counting entries is useless: ten full images use more memory than a thousand thumbnails. Give the cache a limit in bytes, and never go over it.”

Starting point. Step 2 of the cache study (expiry and the shared SynchronizedCache included), in examples/case-studies/cache-eviction/step-2/.

Questions to settle first.

  1. What counts toward the limit: the value’s bytes only, or the key and the cache’s own bookkeeping too? Who knows the size of a value?
  2. What happens to a value larger than the whole limit: refused, or stored after evicting everything?
  3. When a key is overwritten with a larger value, may that key’s own old entry be among the entries evicted to make room?
  4. Should expired entries be removed first, before any live entry is evicted?
Show the hints
  • Types and invariants affected: Cache<K, V> and the EvictionPolicy<K> interface, whose victim() names one key. New invariant: the sum of the sizes of the entries equals the cache’s total, and the total is never above the limit.
  • Keep “choose the victim first”. The study’s put chooses its victim before it changes anything, so that a failure leaves the cache unchanged. With bytes, put must know every victim before it evicts any, and must know that enough room can be made at all.
  • The policy may need a new question. Asking victim() repeatedly without removing anything returns the same key. Either the policy learns to list victims in order, or put removes and can undo, which is harder to make safe.
  • First test: a cache of 100 bytes holding three entries of 30, and a put of 50 that must evict two, in the policy’s order; then a put larger than the limit, which follows your answer to question 2 and leaves the cache as it was if refused.
Show the evaluation criteria

A good solution shows:

  • That a failed put (refused, or a size function or policy that throws) leaves the entries, the total, and the counts unchanged, by a test like the study’s failure tests.
  • A model-based or random test in which the total always equals the sum of sizes and never exceeds the limit, for each policy.
  • For the shared cache: that the size function runs under the one lock, and the stated rule that it must be quick and must not call back into the cache.

Acceptable designs include:

  • A size function given when the cache is made, such as a std::function from a key and value to a byte count. Run-time flexibility, as with the policy; the cost is an indirect call per put and a function the caller must keep honest.
  • A size given with each put. No function to store, and the caller usually knows the size; the cost is that an overwrite must remember the old size, and a wrong size from one caller breaks the limit for everyone.
  • A template parameter for the size rule, like a traits type. No indirect call; the cost is the one the study weighs in A run-time policy or a template parameter?, a different type per rule.

Common mistakes: evicting entries one by one until the new value fits, and only then finding that it cannot fit, so entries were lost for nothing; counting the old size of an overwritten key twice; and assuming every entry is the same size somewhere in the eviction loop.

CS-06 Notification service: send at a later time

Section titled “CS-06 Notification service: send at a later time”

Builds on: the Scope, which puts “scheduling a message for later” out of scope.

The changed requirement.

“We want appointment reminders: the booking system tells you now, but the text should go out 24 hours before the appointment. If the appointment is cancelled, the reminder must not go out.”

Starting point. Step 2 of the notification service study (quiet hours and rate limits included), in examples/case-studies/notification-service/step-2/.

Questions to settle first.

  1. A reminder is due during the user’s quiet hours. Does it wait until they end, as other non-required messages do?
  2. Is the message rendered when it is scheduled, or when it is sent? If the user changes their phone number in between, which number is used?
  3. The caller sends the same id twice with different send times. Is the second a repeat (nothing new), a change of time, or a conflict?
  4. What does cancel do once the first attempt has been made and a retry is waiting?
Show the hints
  • Types affected: the notifier’s schedule, due_, a std::multimap from a time to a pending delivery, which the study calls “a schedule, not a queue”, and the records kept per notification id and channel. A scheduled first send is a new reason for an entry to be in that schedule, or a reason for a second one.
  • A wait is not an attempt. Step 2 already has this rule for quiet hours (FR-9); a scheduled send should not use up a retry either.
  • Render first, or not? Read Render everything first before you answer question 2: it explains why step 1 renders before any attempt, and what changes if the message waits a day.
  • First test: schedule a reminder; run_due before the time sends nothing; at the time, it sends once; a second, cancelled reminder never sends, and its record says it was cancelled.
Show the evaluation criteria

A good solution shows:

  • Tests that put a scheduled send inside quiet hours and over a rate limit, so the new wait combines with the existing ones in the order your requirements give.
  • That the repeat rule still holds: a repeated id sends nothing new, and your answer to question 3 is tested.
  • That cancelling leaves nothing behind in the schedule, including a pending retry if your answer to question 4 says so.
  • A statement that the schedule is in wall-clock time, with the limitation the study already gives for clock changes, and still in memory only.

Acceptable designs include:

  • One schedule whose entries say why they wait (a later attempt, as today, or a scheduled first send), so all waiting work is in one time-ordered place and run_due stays the only way work happens later. The cost is that each entry carries more, and every branch in run_due must handle every tag.
  • A separate list of scheduled sends that run_due turns into ordinary notify calls when they are due. Step 2’s code is barely touched; the cost is two time-ordered structures, and the question of which runs first when both are due.

Common mistakes: rendering with data that may change and not saying so; counting the wait as an attempt; cancel removing the record but not the schedule entry; and a scheduled send that bypasses the opt-out check because preferences were read when it was scheduled.

CS-07 ATM workflow: several note denominations

Section titled “CS-07 ATM workflow: several note denominations”

Builds on: the Scope, which puts “cassettes of several denominations” out of scope, and the Production limitations: “One denomination. A real dispenser chooses notes from several cassettes, and can run out of one.”

The changed requirement.

“Our new machines have two cassettes, 20s and 50s. A customer can take any amount the notes inside can make, and should get as few notes as possible.”

Starting point. Step 2 of the ATM study (daily limit and deposits included), in examples/case-studies/atm/step-2/.

Questions to settle first.

  1. Which amounts can a customer ask for? Is 30 refused at the keypad (it cannot be made from 20s and 50s), and is that decided before the bank is asked to hold anything?
  2. Is “as few notes as possible” the only rule, or must the machine also keep some 20s in reserve so that later customers can be served?
  3. After a jam, does the operator count each cassette separately?
  4. What does the journal record: the amount, or the notes of each kind?
Show the hints
  • Types affected: CashDispenser, whose notes_left() and dispense(int notes) count notes of one kind. That interface has to change, and so does the fake dispenser and every test that sets one up.
  • The order of a withdrawal stays: hold at the bank, dispense, then commit or release. Check that the amount can be made before the hold, so that an impossible amount never reaches the bank.
  • The search is not greedy. 60 from 50s and 20s cannot start with a 50, but three 20s work. The vending machine study explains the same trap in Change: why largest-first is not enough.
  • First test: 70 gives one 50 and one 20; 60 gives three 20s; 30 is refused with no bank call; and an amount that needs the empty cassette is refused when one runs out.
Show the evaluation criteria

A good solution shows:

  • That every existing failure case still holds per stage (no answer from the bank, a jam, a power cut with recovery from the journal), with notes of more than one kind.
  • That recovery after a restart knows what was meant to be dispensed, from the journal alone.
  • That the choice of notes is a pure function, tested without any device, including the cases where greedy fails.
  • That the machine is still driven from one thread (NFR-4).

Acceptable designs include:

  • The ATM chooses the notes, and the dispenser takes a count per denomination. The choice is testable without hardware and can be journalled before the cash moves; the cost is that the ATM must know what each cassette holds.
  • The dispenser chooses from an amount and reports what it gave. Closer to some hardware; the cost is that the “unknown amount” outcome of a jam is harder to reason about, and the choice is tested only through the fake.

Common mistakes: a greedy choice; refusing an impossible amount only after the bank hold, so the hold has to be released; and journalling the amount but not the notes, so a count after a jam cannot be checked against the plan.

CS-08 Shopping cart and checkout: give up on a waiting order

Section titled “CS-08 Shopping cart and checkout: give up on a waiting order”

Builds on: the Production limitations: “Waiting orders wait for ever. An order with a lost answer holds its stock and its coupons until a retry gets an answer. A real shop gives up after a time, asks the provider for the charge’s status, and either settles or cancels it.”

The changed requirement.

“Last week a provider outage left forty orders waiting for two days, holding the last of our kettles. After 30 minutes without an answer, find out whether the customer was charged. If they were, the order is paid. If they were not, cancel it and put the stock and the coupons back.”

Starting point. Step 2 of the shopping cart study (coupons included), in examples/case-studies/shopping-cart/step-2/.

Questions to settle first.

  1. How does the shop find out? Does the provider offer a status query by key, or must the shop send the same charge with the same key again?
  2. Is a cancelled order a new status, or is it the same as payment_failed? What does the customer see?
  3. What if the status query also gets no answer?
  4. Who runs the check, and how often? (In the study, retry_payments is called by whatever schedules background work.)
Show the hints
  • Types affected: OrderStatus (awaiting_payment, paid, payment_failed) and Order, which must now remember when it began waiting; PaymentGateway, which has only charge today; and the fake gateway and its contract tests.
  • Time comes in from outside. Pass the current time in, or inject a clock, as other studies do; a test must not wait 30 minutes.
  • Freeing must match holding. The stock reservation is in Inventory, and the coupon hold in CouponBook. A cancellation must release both, once, and a second call must change nothing.
  • First test: an order waits; the fake says “not charged” after the limit; the order is cancelled and the kettle and the coupon are free again. Then the same with “charged”, which ends paid.
Show the evaluation criteria

A good solution shows:

  • That no order is cancelled without the shop first learning that the customer was not charged, and a test of the “still no answer” case from question 3.
  • That running the check twice, or alongside retry_payments, cannot release stock or coupons twice.
  • Tests at the limit: an order at exactly 30 minutes, and one just before.
  • A statement that the design is still one request at a time (NFR-4), and what a concurrent version would need.

Acceptable designs include:

  • A status query on PaymentGateway by idempotency key. The answer is explicit and cannot charge anyone; the cost is a new method that every gateway, real and fake, must implement and test.
  • Repeating charge with the same key, relying on the provider to return the first answer. No interface change; the cost is that it is safe only while the provider still remembers the key, so the design must state that window and stay inside it.

Common mistakes: cancelling on time alone, which can keep a customer’s money and sell their kettle to someone else; freeing the stock but not the coupons; and a cancelled order that later receives “charged” with no defined outcome (state one, even if it is “flag for a refund by hand”).

CS-09 Expense sharing: delete and edit an expense

Section titled “CS-09 Expense sharing: delete and edit an expense”

Builds on: the Scope, which puts “editing or deleting an expense” out of scope, and the Production limitations: “The group keeps only balances. It cannot list, edit, or delete an expense … A real app would store expenses and transfers as records and derive balances from them.”

The changed requirement.

“Someone typed 450 instead of 45 for the taxi, and now we have to add a fake expense to cancel it. Let us see the list of expenses, delete one, or fix its amount or its split.”

Starting point. Step 2 of the expense sharing study (several currencies at fixed rates included), in examples/case-studies/expense-sharing/step-2/.

Questions to settle first.

  1. Can an expense be edited after the group has recorded transfers that settled it? Does the plan change?
  2. Is a deleted expense gone, or kept and marked deleted so that the group can see what happened?
  3. An edit that makes the expense invalid (a split that does not add up) is refused. Does the old expense stay exactly as it was?
  4. How is an expense identified once others are deleted?
Show the hints
  • Types and invariants affected: the Group, which keeps a balance per member and nothing else. Invariant to keep: the balances add up to exactly zero, after any sequence of adds, edits, and deletes.
  • Undoing needs the shares that were applied, not shares worked out again. The rounding rule in allocate gives the left-over cents to members in a stated order, so reversing an expense must subtract the exact cents it added. Store them, or rebuild every balance from the records.
  • Conversion stays in one place. In step 2, to_base is the one point where an amount moves between currencies; an edit converts again there, at the same fixed rate.
  • First test: add three expenses, delete the middle one, and check that the balances equal those of a group that only ever had the other two. Then extend the study’s zero-sum random test with deletes and edits.
Show the evaluation criteria

A good solution shows:

  • That a refused edit is a Rejection and leaves the group exactly as it was, like every other refusal in the study.
  • The property “a group after deleting an expense equals a group that never had it”, tested on random sequences.
  • Stable expense ids that do not shift when another expense is deleted.
  • That ownership is simple and stated: the group owns its records by value.

Acceptable designs include:

  • Store the records and derive the balances from them, on every change or on demand. Deleting and editing become list operations, and the balances cannot drift from the records; the cost is work that grows with the number of expenses, which is small for a trip.
  • Keep the running balances and store each expense’s applied shares, so that a delete subtracts them and an edit subtracts the old and adds the new. Constant work per change; the cost is two sources of truth that a test must keep in step.

Common mistakes: reversing an expense by splitting its amount again, which can differ by a cent; ids that are positions in a vector; and an edit that subtracts the old shares before checking the new ones, so a refused edit leaves the group changed.

CS-10 Booking and ticket reservation: prices by seat category

Section titled “CS-10 Booking and ticket reservation: prices by seat category”

Builds on: the Scope, which puts “seat maps with sections and prices per seat” out of scope, and the Production limitations: “One price per show. Every seat costs the same, and there are no discounts, fees, or seat categories.”

The changed requirement.

“Front stalls cost 60, the rest of the stalls 45, and the circle 30. A customer’s hold should show the total, and the price they are charged must be the price they saw when they held the seats, even if we change prices in the meantime.”

Starting point. Step 2 of the ticket reservation study (group holds included), in examples/case-studies/ticket-reservation/step-2/.

Questions to settle first.

  1. May the box office change a category’s price while the show is on sale? (The quote suggests so.)
  2. A group asks for “four together”. May the four span two categories, or must they be in one? Which category is tried first?
  3. The quote fixes the price when the seats are held. If a price falls before the customer confirms, do they still pay the higher price they saw?
  4. Are seats assigned to categories once, at setup, like the shows?
Show the hints
  • Types affected: Seat, Show (whose single price_per_seat_ is const today), GroupRequest, and the group seat-choosing rule, which today picks the front-most row with a block and the lowest seat numbers. A Hold already carries an amount, and begin_confirm hands that amount to the payment as PaymentDue; check whether the hold-time price rule in the quote is already met.
  • The amount is fixed under the lock. The study keeps the payment call outside the show’s mutex; see No lock during the payment. Keep working out the amount while the lock is held, and keep the charge reading it from the hold.
  • A price change is a write to shared data. Today the price is const, so reading it needs no thought. If prices can change during the sale, they must be protected by the same mutex as the seats, or be immutable and replaced as a whole.
  • First test: hold two seats in different categories and check the total; change a price; confirm; the gateway is charged the old total.
Show the evaluation criteria

A good solution shows:

  • That the existing thread tests still pass, and a new one changes a price on one thread while others hold and confirm, run under the tsan preset, with no data race and every charge equal to the held amount.
  • That the group rule is still fixed and documented, so a test can name the seats it picks, with your answer to question 2.
  • That money stays in Cents, as in the study, never a floating-point number.

Acceptable designs include:

  • A category per seat and a price table per show, read under the show’s lock. One place to change a price; the cost is that every price read must happen with the lock held.
  • A price stored on each seat. Simple reads; the cost is that a category’s price change touches many seats, and the category is no longer a thing the code can name.
  • An immutable price table replaced as a whole (for example, behind a std::shared_ptr<const PriceTable> swapped under the lock). A hold keeps the table it used; the cost is one more shared ownership to explain.

Common mistakes: working out the amount at confirm after the lock is released; reading a price that another thread may be writing; and letting a group block cross categories without the requirement saying so.

CS-11 Task scheduler: forget finished tasks

Section titled “CS-11 Task scheduler: forget finished tasks”

Builds on: the Production limitations: “Records are never erased. Each finished task keeps its record and its queue node for the life of the scheduler, so a long-running service that schedules millions of tasks needs a way to forget old ones (for example, a record erased once its info has been read, or after a time).”

The changed requirement.

“Our service schedules a few thousand run-once tasks an hour and runs for months. Memory keeps growing. Forget a task an hour after it finishes; nobody asks about a task that old.”

Starting point. Step 2 of the task scheduler study (retries and dependencies included), in examples/case-studies/task-scheduler/step-2/.

Questions to settle first.

  1. What does info return for a forgotten task, and what does cancel return: unknown_task, or already_finished? Can a caller tell a forgotten task from one that never existed, and do they need to?
  2. A new task names a forgotten task as a dependency. Is that refused, or treated as “it succeeded”? Can you even know which?
  3. Is “an hour after it finishes” measured on the scheduler’s clock? When is the forgetting done, and by which thread?
  4. Periodic tasks finish only when cancelled. Does the rule apply to them from then on?
Show the hints
  • Types affected: the scheduler’s records, its queue nodes, and the callables they keep alive. info already returns std::optional<TaskInfo>, and CancelResult already has unknown_task, so the public types may not need to change.
  • Destroying a task is not just freeing memory. A task that will never run again normally has its callable destroyed at once, with the lock released. But the study warns that callables of tasks cancelled because of a dependency (or by shutdown) stay in their records and are destroyed only with the scheduler. Forgetting such a record destroys its callable: make sure that happens outside the scheduler’s lock, for example by moving it out under the lock and letting it go after the lock is released.
  • Dependencies point at records. In step 2, a finished task may still matter to tasks waiting on it. Only forget a record that no waiting task needs, or record the outcome somewhere smaller first.
  • First test: run a task to success, advance the test clock by an hour, and check that info returns nothing; then a task cancelled because its dependency failed, whose callable’s destructor calls the scheduler, forgotten the same way, which must not deadlock.
Show the evaluation criteria

A good solution shows:

  • That the step 1 and step 2 tests still pass, including the forced-order and thread tests, and that the tsan preset still passes.
  • A test that memory is bounded in the sense that matters: after many tasks finish and the retention time passes, the number of records returns to what is pending.
  • A test for each answer to questions 1, 2, and 4.
  • A clear statement of which lock is held while records are erased, and that no callable is destroyed with it held.

Acceptable designs include:

  • An explicit sweep, such as a forget_finished call the owner makes from time to time. Predictable and easy to test; the cost is that a caller who never calls it has the old behaviour.
  • Forgetting as part of normal work, for example when a worker takes the scheduler’s lock to pick the next task. No new call for users; the cost is extra work on a hot path, and a harder proof that nothing is destroyed under the lock.
  • Erasing a record once its final info has been read, as the study suggests. Very little state; the cost is that a second reader is surprised, so it only suits a single, known reader.

Common mistakes: destroying callables while holding the lock; forgetting a task that a waiting task still depends on; erasing the record of a running task; and a sweep that walks every record with the lock held for a long time, which the study already lists as a cost elsewhere.

CS-12 Elevator system: hand a call to a better car

Section titled “CS-12 Elevator system: hand a call to a better car”

Builds on: the Production limitations: “Hall calls are never reassigned. A call stays with its car even when a better one becomes free.”

The changed requirement.

“People on floor 9 wait for car B, which is ten stops away, while car C sits idle on floor 8. If another car can clearly get to a waiting call sooner, give the call to that car.”

Starting point. Step 2 of the elevator study (express cars and maintenance mode included), in examples/case-studies/elevator/step-2/.

Questions to settle first.

  1. What does “clearly sooner” mean? A margin stops a call from moving back and forth between two cars. Under nearest_car the cost is a distance, so a margin in floors or ticks makes sense; under least_busy it is not a travel time, so decide what the margin means for that rule, or allow moves only under one rule.
  2. When is a call reconsidered: on every tick, or only when something changes (a car becomes idle, a car comes back from maintenance)?
  3. Which calls may never move? For example, a call whose car is already stopping at that floor, or has its doors open there.
  4. Does the passenger’s wait start again when the call moves, or does it still count from the button press?
Show the hints
  • Invariants affected: each hall call belongs to exactly one car, and an express car is never given a call on a floor it skips. Both must hold at every step of a move.
  • Reuse step 2. Maintenance mode already takes hall calls away from a car and gives them to others by the usual rule, in the Building, because the building made the promises. Moving a call to a better car is the same operation with a different reason.
  • The rule is a cost. The dispatch rules are a CostRule (nearest_car, least_busy). Reassignment compares costs; it should not invent a second way to estimate them.
  • First test: a trace in which a call is given to a distant car, another car becomes idle next to the caller, and the call moves at the tick your answer to question 2 says; then the same trace with a gap smaller than your margin, in which it does not move.
Show the evaluation criteria

A good solution shows:

  • That the existing traces and random runs still pass, or, where a reassignment changes a trace, that the change is explained by the new requirement.
  • A test that a call never ping-pongs between two cars, and that the express and maintenance rules are respected by every move.
  • That the simulation is still deterministic: the same requests and ticks give the same moves.
  • That it is still one caller on one thread (NFR-5).

Acceptable designs include:

  • Reconsider every waiting call on every tick, with a margin. The simplest rule to state; the cost is work per tick, and traces that change in more places.
  • Reconsider only on events, such as a car becoming idle. Fewer moves and quieter traces; the cost is that a call can stay with a worse car if the better car became better without an event.

Common mistakes: a call held by two cars, or by none, for a tick; moving a call away from a car that has already started to stop for it; and not saying where a moved call’s wait starts. The step 2 random run restarts a call’s wait when maintenance hands it back, because its bound is about how long a car takes once it has the call; if a move restarts the wait too, the test no longer measures the whole wait from the button press, so say which one your test checks.

Builds on: the Scope, which puts “draw offers and resignation” out of scope, and the Production limitations, which list draw offers among the missing draw rules.

The changed requirement.

“Players resign all the time in blitz, and they agree draws. Let a player resign, and let a player offer a draw that the opponent can accept. The PGN must show the result.”

Starting point. Step 2 of the chess study (clocks and PGN export included), in examples/case-studies/chess/step-2/.

Questions to settle first.

  1. The study assumes two players at one screen, and that whoever types the move is the side to move. Who resigns: the side to move only, or either side, named in the request?
  2. How long does a draw offer last? Is it declined by the opponent making a move?
  3. Can a resignation or an agreed draw be taken back? (The club already said that a result on time cannot be.)
  4. Do the clocks stop at once when the game ends this way?
Show the hints
  • Types affected: GameState, which today has wins, draws by stalemate and by the fifty-move rule, and the three results on time; the Refusal values (for “there is no offer to accept”); the PGN result; and Game, which owns the clock and the history.
  • An offer belongs to the game, not the position. Position is what FEN describes and what legality is judged on. An offer is not part of either, so keep it out of Position.
  • Undo already has a policy. Read The undo policy before answering question 3: the same reasoning (what a take-back may give back) applies here.
  • First test: after a resignation the state is the opponent’s win, and every further move is refused with a reason; then an offer followed by a move leaves no offer standing; then an accepted offer is a draw in the PGN result.
Show the evaluation criteria

A good solution shows:

  • That every switch on GameState handles the new values, and the PGN result for each is tested.
  • Tests for your answers to questions 2, 3, and 4, including undo after each kind of ending.
  • That FEN output is unchanged by an offer, which shows it stayed out of the position.

Acceptable designs include:

  • New GameState values, such as a win by resignation for each side and a draw by agreement. Every reason is visible to a caller; the cost is a longer enum and more cases in every switch.
  • A result and a separate reason, where the state says who won and a second field says why. Fewer combinations to list; the cost is that the two must agree, which the type no longer enforces.

Common mistakes: storing the offer in Position; allowing moves after a resignation; and an undo that quietly reopens a game the club’s rules say is over.

Builds on: the Scope, which puts “saving a game” out of scope, and the Production limitations: “No saving or loading. The history of moves would make this easy (a game is its list of columns), but it is not written.”

The changed requirement.

“People want to stop a long game on a big board and finish it tomorrow. Let them save a game to a text file and load it back, so it continues exactly where it stopped, undo included.”

Starting point. Step 2 of the Connect Four study (chosen sizes, undo, and the computer player included), in examples/case-studies/connect-four/step-2/.

Questions to settle first.

  1. What is in the file: the rules (width, height, line length) and the columns played, or a picture of the board? Which one lets undo work after loading?
  2. How is a file from a later version of the program told apart?
  3. The file is text a person can edit. What happens to a file with a column out of range, a move into a full column, or a move after a win?
  4. Does the file say who is the computer player, or is that the program’s choice when it loads?
Show the hints
  • Types affected: few. The game’s rules are checked when a game is made (FR-6), every move is checked before it is made, and the history of moves already exists for undo.
  • Where the change lives: outside Game, in two free functions, one that writes a game and one that reads text and returns a game or a reason. The game does not need to know about files; a test can pass a string.
  • Replay instead of trust. Loading by playing the saved columns through the game’s own move function reuses every check, and gives the undo history for free.
  • First test: a round trip for a finished game and for one in progress: save, load, and compare the board, the player to move, the state, and the result of undoing once.
Show the evaluation criteria

A good solution shows:

  • A round-trip test over many random games and sizes, and a test for each kind of bad file in question 3, each refused with a reason and no game made.
  • That the file format is written down, with its version marker.
  • That reading and writing files is kept out of the rules, so the existing tests are untouched.

Acceptable designs include:

  • Replaying the moves through the public game. Every rule is checked again, and nothing new must be proved; the cost is the time to replay, at most 100 moves on the largest board.
  • A way to build a game from a board and a history, checked against the invariants. Faster for long histories; the cost is a second way to make a game, with its own checks that must match the move checks.

Common mistakes: saving only the board picture, which loses the order of moves and so undo; trusting the file; and putting file input and output inside Game, which ties the rules to storage.

Builds on: the Production limitations: “Secure codes. No secure random source, no rate limit on wrong codes, and codes stored in plain text.”

The changed requirement.

“Someone stood at a locker last night typing codes until one worked. After five wrong codes in ten minutes, the keypad should refuse every code for ten minutes, and our staff log should hear about it.”

Starting point. Step 2 of the parcel locker study (the next size up and listeners included), in examples/case-studies/parcel-locker/step-2/.

Questions to settle first.

  1. What counts as a wrong code: only an unknown code, or also a code already used, or expired?
  2. While the keypad is locked, is a right code refused too? (If not, the lock does not stop guessing.)
  3. Anyone can lock the keypad for everyone by typing five wrong codes. Is that acceptable, and what does a customer at a locked keypad see?
  4. Does the lock apply to couriers, who use a different role?
Show the hints
  • Types affected: PickupRefusal (today unknown_code, code_already_used, and code_expired) gains a reason, with its to_string; LockerBank or a new class keeps recent wrong attempts; the time comes from the injected Clock.
  • Listeners: LockerListener has one virtual function per event, each with an empty default body, so adding an event for a lockout does not break existing listeners. Listeners are called inside the operation, on the same thread.
  • Roles: the customer’s path goes through CustomerAccess. Make sure the limit cannot be skipped by any other path to a pickup.
  • First test: five wrong codes, then the right code is refused with the new reason; after ten minutes on the test clock, the right code opens the door.
Show the evaluation criteria

A good solution shows:

  • Tests at the boundaries: four wrong codes and then the right one (opens), five (locks), and the moment the lock ends.
  • That a locked keypad changes no parcel and no compartment, and that expiry and courier collection still work if your answer to question 4 says so.
  • A statement that the bank is still single-threaded, and of what the limit does not protect against (it is a delay, not a secure code).

Acceptable designs include:

  • The count kept in LockerBank, next to the code lookup. The rule is beside the operation it guards; the cost is that the bank grows another responsibility.
  • A small attempt-limiter class that the bank owns and asks before each pickup, tested alone with its own clock. The rule is separate and reusable; the cost is one more type, and the bank must still be the only way in.

Common mistakes: counting the attempt only after a right code, so the lock never starts; a lock that also blocks couriers from collecting expired parcels without saying so; and keeping every wrong attempt for ever, which adds to the growth the study already lists.

CS-17 In-memory file system: a current directory

Section titled “CS-17 In-memory file system: a current directory”

Builds on: the Scope, which puts “a current directory and relative paths” out of scope.

The changed requirement.

“Typing full paths in the sandbox is tiring. Give each session a current directory, a cd command, and paths that do not start with a slash, relative to it.”

Starting point. Step 2 of the file system study (sizes, quotas, and find included), in examples/case-studies/file-system/step-2/.

Questions to settle first.

  1. A session is in /work/tmp, and another session runs rm on /work recursively. What happens to the first session?
  2. The current directory is moved with mv. Does the session follow the directory to its new name, or stay at the old path?
  3. The study refuses .. at the root. Is cd .. at the root still refused, or does it stay at the root as most shells do? And is a relative path with .. resolved from the current directory’s node, or from its path?
  4. How many sessions can there be, and who owns each one?
Show the hints
  • Ownership is the heart of this challenge. The tree is a tree of std::unique_ptr, and each node has a plain pointer to its parent that owns nothing. A session that keeps a plain pointer to its current directory can be left pointing at freed memory by rm.
  • Two safe shapes: keep the current directory as an absolute path and resolve it on every command, or keep a pointer and have the file system know every session, so rm and mv can update or refuse.
  • Path resolution: today paths are absolute. A relative path can become an absolute one by putting the current directory in front, and then the existing resolution, with . and .., does the rest.
  • First test: cd /a, mkdir b, and ls /a shows b; then remove /a while a session is in it, and check the result you chose in question 1, under the asan-ubsan preset.
Show the evaluation criteria

A good solution shows:

  • A test for each answer to questions 1, 2, and 3, run under AddressSanitizer, with no use of freed memory.
  • That every existing command behaves exactly as before for absolute paths.
  • That the ownership of sessions and of the current directory is stated: who owns a session, and what keeps its current directory valid, or why it does not need to be.

Acceptable designs include:

  • The current directory as a path string, resolved again on each command. Nothing can dangle; the cost is that a moved directory is not followed, and a removed one is found only at the next command.
  • A pointer to the directory, with the file system tracking sessions, so rm of a directory with a session inside is refused (or resets the session) and mv is followed. Closer to how a real shell feels; the cost is a registry of sessions and a lifetime rule (a session must not outlive the file system) that must be stated and tested.

Common mistakes: a plain pointer to the current directory with no plan for rm; one current directory stored in the FileSystem itself, which fails as soon as there are two sessions; and treating relative paths in a second resolver instead of reusing the first.

CS-18 Inventory management: stock in transit

Section titled “CS-18 Inventory management: stock in transit”

Builds on: the Production limitations: “Transfers are instant. Real stock spends days on a lorry, where it is in neither warehouse; that needs an ‘in transit’ count.”

The changed requirement.

“A transfer from Leeds to York takes two days. When the lorry leaves, the stock is no longer in Leeds; when it arrives, York counts it in. Sometimes a few boxes are damaged on the way, and York records fewer than were sent.”

Starting point. Step 2 of the inventory study (batches with expiry dates and instant transfers included), in examples/case-studies/inventory/step-2/.

Questions to settle first.

  1. Can York reserve stock that is still on the lorry?
  2. A batch expires while it is in transit. Is it still received, and does it then count as expired stock at York?
  3. Receiving is done by a person scanning a delivery. Is “receive” safe to repeat, as commit and release are today?
  4. Where do damaged units go: written off with a record, or just missing from the count?
Show the hints
  • Invariants affected: each warehouse’s on hand and reserved counts, per batch. New invariant: for each product, the units in all warehouses plus the units in transit plus the units recorded as damaged stay equal to what came in from suppliers, minus what was shipped to customers.
  • A transfer has states, like a reservation: in transit, then received or lost. The study’s reservation state machine, with commit and release that are safe to repeat, is the model to copy.
  • Same lock, same alert rule. Everything is behind one mutex today, and low-stock alerts are sent once per crossing, after the lock is released. Dispatch can make Leeds cross its threshold; receipt can take York back above it. Neither may send an alert with the lock held.
  • First test: dispatch from Leeds; Leeds’s available count falls; York’s is unchanged; receive; York’s rises by the received number; a second receive changes nothing.
Show the evaluation criteria

A good solution shows:

  • The conservation property above, checked after every step of a random test.
  • A test with threads in which a receipt at York races with an order for the last unit there, run under the tsan preset, with the answer your requirements give.
  • That batches keep their expiry dates through the lorry, and the first-expiry-first-out rule still holds at York.
  • That alerts are still once per crossing and outside the lock.

Acceptable designs include:

  • A Transfer record owned by the inventory, holding the batches it carries, with its own states and id. In-transit stock is in no warehouse, so it cannot be reserved by accident; the cost is a new type and a new state machine to test.
  • An “in transit” warehouse per route, so a transfer is two of today’s instant transfers. Reuses tested code; the cost is a warehouse that is not a real place, which every report and every reservation must be told to skip.

Common mistakes: a receive that is not safe to repeat; losing a batch’s expiry date by merging it into the destination’s stock; a second mutex for transfers, which brings lock order into a design that avoided it; and alerts sent with the lock held.

Go through this list for each challenge you finish. It is a self-review, not a grade; the point is to find the gaps before someone else does.

  • I wrote the requirements and acceptance criteria before the code, and each new test names the criterion it checks.
  • I recorded my answer to every question, and marked which answers are assumptions.
  • The study’s existing tests pass, and I can explain every test I had to change by a requirement that changed.
  • I can list every file and type I changed, and say why each one had to change.
  • For every new member, pointer, or reference, I can say who owns it and why it lives long enough.
  • Where the study has threads, I said which lock protects the new data, checked that nothing slow or re-entrant runs with it held, and ran the thread tests under the tsan preset.
  • Refusals are values with reasons, as in the study, and a refused request changes nothing.
  • I considered at least one other design, and can say what would make it the better choice.
  • I added nothing that no requirement asked for.

For a wider view of where you stand, use the design-readiness checklist, before and after a few challenges. For more practice of other kinds, see the practice hub. To revisit the method the studies follow, see How to approach a case study.

  • Each challenge is a realistic next change for one study, built on a limitation the study states, and sized for a few hours.
  • Settle the questions, write the acceptance criteria, keep the study’s tests green, and test the new criteria first.
  • The evaluation criteria describe what a good solution shows, and name at least two acceptable designs; they are not a single model answer.
  • A good solution is local, or justifies its spread, and states ownership, lifetimes, and, where there are threads, locking.