Skip to content

C++ refactoring exercises

Difficulty: Intermediate

Key concepts

  • refactoring
  • characterization test
  • small steps
  • extract function
  • seam
  • RAII
  • unique_ptr
  • exception safety
  • std::variant
  • type code
  • How to change the structure of working C++ code without changing what it does, by keeping a set of tests green after every small step.
  • Four refactorings, each on a different small program: extract function, introduce a seam, replace raw owning pointers with std::unique_ptr, and replace a type code with std::variant.
  • For each step, which test or which compiler check would have caught a mistake, so you can tell a safe step from a lucky one.
  • When each refactoring is not worth doing.

This page is practice for two lessons. Read Refactoring safely in small steps and Refactoring toward principles first: their method, a test that pins the behaviour first and then one small step at a time, is the method here.

The code for every task is in the examples project, in examples/practice/refactoring/ (one folder per task, each with a start and a solution folder). The whole project, with its build files, is one download, lld-examples.tar; Building and running the examples yourself lists what it needs. Build it once, then run one task’s tests by name:

Terminal window
tar -xf lld-examples.tar
cd lld-examples
cmake --preset gcc-debug
cmake --build --preset gcc-debug
ctest --preset gcc-debug -R prc_refactor_receipt # task 1; see each task for its name

Each task has three test programs. The start one runs the characterization tests against the start code. The solution one runs the same source file, unchanged, against the reference solution. The third tests what the refactoring made possible. Work in the start folder; the solution is there to compare with afterwards.

  1. Build the start code and run its tests. They pass. If they did not, you would not know whether a later failure came from your change.
  2. Read the start code and the tests. The tests are the net: what they pin cannot change without a red test. Note what they do not pin, because a step there is not protected.
  3. Take the smallest step that moves toward the goal: one function extracted, one member’s type changed, one call site switched.
  4. Build and run the tests. Green: take the next step. Red: undo the step and take a smaller one. Debugging a step that went wrong costs more than redoing it in two halves.
  5. Never edit a characterization test to make it pass. A test that has to change means the behaviour changed, and that is a separate decision, not part of a refactoring.

If you use version control, commit after each green step, so undo is one command. Run the tests under the asan-ubsan preset too, at least before you finish. For task 3 this matters most: AddressSanitizer turns a leak or a double delete in a tested path into a failed test.

In every task the tests use only the code’s public interface: the functions and classes the rest of a program would call. Those keep their names and signatures, and for every input the tests use, they keep their results, their output to the character, and their exceptions. Everything behind them may change: new functions, new types, new files. Task 3 also removes two things that were broken, on purpose, and says so.

The start code is labelled Flawed (intentional) because it is not code to copy: its structure is the thing to fix, and in task 3 it also has two real bugs that no test reaches. Unlike most flawed code on this site, it is run: for the calls its characterization tests make it works, and those tests pass in the recorded test run. The solutions are labelled from that run too. The characterization tests are shown with the solution’s label, because the same file is compiled and run against the solution.

Difficulty: the gentlest. Refactoring: extract function, then separate working out the numbers from formatting them. Tests: ctest -R prc_refactor_receipt.

A shop’s till prints a receipt from one function, receipt. It works, but the shop wants to test its pricing rules (3 for 2, two coupons, VAT) with numbers, and to add a second layout for email receipts later. Today every rule can only be checked by comparing a whole receipt as text, and the money formatting is written out five times. Split it so that each rule has a name and can be tested alone, and the numbers exist before any text.

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

receipt.hpp
// PRC-08 task 1, start code. It works, and the characterization tests in
// tests/characterization.cpp pass, but one long function checks the input,
// applies the 3-for-2 rule, two coupons, and VAT, and formats the text, all
// mixed together. The money formatting is written out five times. None of the rules
// can be tested without comparing the whole receipt text.
#pragma once
#include <cstdint>
#include <stdexcept>
#include <string>
#include <vector>
namespace prc_refactor_receipt {
// One line of a shopping cart: what was bought, its price, and how many.
struct CartLine {
std::string name;
std::int64_t unit_pence = 0; // price of one item, in pence
int quantity = 0;
};
// Builds the till receipt for a cart and an optional coupon code ("" for
// none). Throws std::invalid_argument for a quantity below 1 or a negative
// price. Every third item of the same line is free ("3 for 2"). SAVE10 takes
// 10% off, rounded down to the penny; FIVEOFF takes 5.00 off a subtotal of
// at least 20.00. Prices include VAT at 20%, so the VAT part is one sixth of
// the total, rounded down.
inline std::string receipt(const std::vector<CartLine>& lines, const std::string& coupon) {
std::string out;
std::int64_t subtotal = 0;
int items = 0;
for (const CartLine& line : lines) {
if (line.quantity < 1) {
throw std::invalid_argument("quantity must be at least 1: " + line.name);
}
if (line.unit_pence < 0) {
throw std::invalid_argument("price must not be negative: " + line.name);
}
std::int64_t cost = line.unit_pence * line.quantity;
// 3 for 2: one item free for each full group of three.
if (line.quantity >= 3) {
cost -= (line.quantity / 3) * line.unit_pence;
}
subtotal += cost;
items += line.quantity;
// Pounds, a dot, then two digits of pence: 1205 becomes "12.05".
std::string amount = std::to_string(cost / 100) + "." +
(cost % 100 < 10 ? "0" : "") + std::to_string(cost % 100);
out += line.name + " x" + std::to_string(line.quantity) + " " + amount + "\n";
}
std::int64_t discount = 0;
if (coupon == "SAVE10") {
discount = subtotal / 10; // integer division rounds down
} else if (coupon == "FIVEOFF") {
if (subtotal >= 2000) {
discount = 500;
}
} else if (!coupon.empty()) {
out += "Coupon " + coupon + " not recognised\n";
}
const std::int64_t total = subtotal - discount;
out += "Items: " + std::to_string(items) + "\n";
out += "Subtotal " + std::to_string(subtotal / 100) + "." +
(subtotal % 100 < 10 ? "0" : "") + std::to_string(subtotal % 100) + "\n";
if (discount > 0) {
out += "Discount -" + std::to_string(discount / 100) + "." +
(discount % 100 < 10 ? "0" : "") + std::to_string(discount % 100) + "\n";
}
out += "Total " + std::to_string(total / 100) + "." + (total % 100 < 10 ? "0" : "") +
std::to_string(total % 100) + "\n";
const std::int64_t vat = total / 6; // the VAT inside a price that includes 20%
out += "of which VAT " + std::to_string(vat / 100) + "." + (vat % 100 < 10 ? "0" : "") +
std::to_string(vat % 100) + "\n";
return out;
}
} // namespace prc_refactor_receipt

The characterization tests compare the whole receipt text for eight carts: plain lines, 3 for 2 with SAVE10, the rounding of SAVE10, FIVEOFF on each side of 20.00, an unknown coupon (codes are case-sensitive), one pence digit, an empty cart, and the three refusals.

Show the characterization tests for task 1

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

characterization.cpp
// PRC-08 task 1: characterization tests. They pin what receipt() prints
// today, right or wrong, so that a refactoring that changes any character
// fails. The same file is built against start/ and against solution/.
#include "lld_test.hpp"
#include "receipt.hpp"
#include <stdexcept>
#include <string>
using namespace prc_refactor_receipt;
LLD_TEST(prints_each_line_then_the_totals) {
LLD_CHECK_EQ(receipt({{"Tea", 250, 2}, {"Mug", 899, 1}}, ""),
std::string("Tea x2 5.00\n"
"Mug x1 8.99\n"
"Items: 3\n"
"Subtotal 13.99\n"
"Total 13.99\n"
"of which VAT 2.33\n"));
}
LLD_TEST(three_for_two_and_save10) {
// 7 biscuits: two full groups of three, so two are free.
LLD_CHECK_EQ(receipt({{"Biscuits", 120, 7}}, "SAVE10"),
std::string("Biscuits x7 6.00\n"
"Items: 7\n"
"Subtotal 6.00\n"
"Discount -0.60\n"
"Total 5.40\n"
"of which VAT 0.90\n"));
}
LLD_TEST(save10_rounds_the_discount_down) {
LLD_CHECK_EQ(receipt({{"Pen", 1999, 1}}, "SAVE10"),
std::string("Pen x1 19.99\n"
"Items: 1\n"
"Subtotal 19.99\n"
"Discount -1.99\n"
"Total 18.00\n"
"of which VAT 3.00\n"));
}
LLD_TEST(fiveoff_needs_a_subtotal_of_twenty_pounds) {
LLD_CHECK_EQ(receipt({{"Book", 2000, 1}}, "FIVEOFF"),
std::string("Book x1 20.00\n"
"Items: 1\n"
"Subtotal 20.00\n"
"Discount -5.00\n"
"Total 15.00\n"
"of which VAT 2.50\n"));
LLD_CHECK_EQ(receipt({{"Book", 1999, 1}}, "FIVEOFF"),
std::string("Book x1 19.99\n"
"Items: 1\n"
"Subtotal 19.99\n"
"Total 19.99\n"
"of which VAT 3.33\n"));
}
LLD_TEST(an_unknown_coupon_is_reported_after_the_lines) {
// Coupon codes are case-sensitive today: "save10" is not SAVE10.
LLD_CHECK_EQ(receipt({{"Tea", 250, 1}}, "save10"),
std::string("Tea x1 2.50\n"
"Coupon save10 not recognised\n"
"Items: 1\n"
"Subtotal 2.50\n"
"Total 2.50\n"
"of which VAT 0.41\n"));
}
LLD_TEST(small_amounts_keep_two_digits_of_pence) {
LLD_CHECK_EQ(receipt({{"Sweet", 5, 1}}, ""),
std::string("Sweet x1 0.05\n"
"Items: 1\n"
"Subtotal 0.05\n"
"Total 0.05\n"
"of which VAT 0.00\n"));
}
LLD_TEST(an_empty_cart_prints_zero_totals) {
LLD_CHECK_EQ(receipt({}, ""), std::string("Items: 0\n"
"Subtotal 0.00\n"
"Total 0.00\n"
"of which VAT 0.00\n"));
}
LLD_TEST(refuses_a_bad_quantity_or_price) {
LLD_CHECK_THROWS(receipt({{"Tea", 250, 0}}, ""), std::invalid_argument);
LLD_CHECK_THROWS(receipt({{"Tea", -1, 1}}, ""), std::invalid_argument);
// The bad line is refused even after good lines.
LLD_CHECK_THROWS(receipt({{"Mug", 899, 1}, {"Tea", 250, -2}}, ""), std::invalid_argument);
}
  • receipt(lines, coupon) keeps its signature, its text to the character, and its std::invalid_argument for a bad line.
  • CartLine keeps its fields. Anything else may be added.
  • Do not fix anything on the way. If you find something you think is wrong, such as the case-sensitive coupon codes, write it down; it is a separate change.
Show hints for task 1
  • Start with the duplication that is easiest to see: the five copies of “pounds, a dot, two digits of pence”. Replace one copy at a time.
  • Each rule (3 for 2, a coupon, VAT) can become a function from numbers to a number. The two checks on a line belong with the line’s cost.
  • The else if chain for coupons does two jobs: it works out the discount, and it decides to print “not recognised”. Those can become two functions.
  • To separate the numbers from the text, you need somewhere to keep the numbers between the two halves: a small struct.
  • Before you change how a rule is computed, check whether the tests would catch a mistake there. The characterization tests only use quantities 1, 2, and 7.
Show the reference solution for task 1

The steps.

  1. Run the tests on the start code. All eight pass. This shows that the net works before anything has changed.
  2. Extract format_pence and replace the five copies one at a time, running the tests after each. Protected by: every amount on every receipt goes through it, and two tests pin the padding: 0.05 (one pence digit) and 0.00 (the empty cart). A version that forgot the leading zero fails both.
  3. Extract line_cost: move the two checks and the cost lines into it, unchanged. Protected by: the refusal test, which also checks that a bad line after a good one is still refused, and the 3-for-2 test.
  4. Write tests for line_cost before changing its formula. The solution computes unit_pence * (quantity - quantity / 3) instead of subtracting the free items. That is equal for every quantity of 1 or more, but the characterization tests only try 1, 2, and 7, so they would not catch every slip in a new formula. The new tests try 1, 2, 3, 5, and 6. Add them, see them pass against the old formula, then change it. Protected by: the new tests, which is why they came first.
  5. Extract coupon_discount and is_known_coupon from the else if chain. Protected by: the SAVE10 rounding test (1.99 off 19.99, not 2.00), the FIVEOFF test on both sides of 20.00, and the unknown-coupon test, which pins both where the “not recognised” line goes and that save10 is not SAVE10.
  6. Extract vat_included_in. One line, but it gives the rule a name.
  7. Separate the numbers from the text. Add PricedLine and PricedCart; then move the loop and the coupon logic into price_cart, which returns a PricedCart, and the text into format_receipt; receipt becomes the two calls. This is the largest step, so do it in two: first fill the struct while the old code still formats as it goes, run the tests, then move the formatting out. Protected by: every exact-text test, including the position of the coupon line, between the items and the totals.
  8. Add the tests the split made possible (below): each rule with numbers, and price_cart without any text.

The result:

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

receipt.hpp
// PRC-08 task 1, reference solution. The same receipt() as the start code,
// with the same output for every cart, split into named functions: one for
// money text, one per pricing rule, one that works out the numbers, and one
// that formats them. The characterization tests (start/tests) pass unchanged;
// tests/test_rules.cpp tests the rules directly.
#pragma once
#include <cstdint>
#include <stdexcept>
#include <string>
#include <vector>
namespace prc_refactor_receipt {
// One line of a shopping cart: what was bought, its price, and how many.
struct CartLine {
std::string name;
std::int64_t unit_pence = 0; // price of one item, in pence
int quantity = 0;
};
// [snippet:rules]
// Pounds, a dot, then two digits of pence: 1205 becomes "12.05". Only used
// for amounts that cannot be negative.
inline std::string format_pence(std::int64_t pence) {
const std::int64_t rest = pence % 100;
return std::to_string(pence / 100) + "." + (rest < 10 ? "0" : "") + std::to_string(rest);
}
// The cost of one cart line after "3 for 2": one item free for each full
// group of three. Throws std::invalid_argument for a quantity below 1 or a
// negative price.
inline std::int64_t line_cost(const CartLine& line) {
if (line.quantity < 1) {
throw std::invalid_argument("quantity must be at least 1: " + line.name);
}
if (line.unit_pence < 0) {
throw std::invalid_argument("price must not be negative: " + line.name);
}
const int paid_items = line.quantity - line.quantity / 3;
return line.unit_pence * paid_items;
}
// What a coupon takes off a subtotal. An unknown or empty code takes nothing
// off; whether to say so on the receipt is the formatter's job.
inline std::int64_t coupon_discount(const std::string& coupon, std::int64_t subtotal) {
if (coupon == "SAVE10") {
return subtotal / 10; // 10%, rounded down to the penny
}
if (coupon == "FIVEOFF") {
return subtotal >= 2000 ? 500 : 0;
}
return 0;
}
inline bool is_known_coupon(const std::string& coupon) {
return coupon == "SAVE10" || coupon == "FIVEOFF";
}
// Prices include VAT at 20%, so the VAT part is one sixth, rounded down.
inline std::int64_t vat_included_in(std::int64_t total) { return total / 6; }
// [/snippet:rules]
// [snippet:priced]
// Every number on the receipt, worked out but not yet formatted.
struct PricedLine {
std::string name;
int quantity = 0;
std::int64_t cost = 0;
};
struct PricedCart {
std::vector<PricedLine> lines;
std::string unknown_coupon; // the code to report, or empty
int items = 0;
std::int64_t subtotal = 0;
std::int64_t discount = 0;
std::int64_t total = 0;
std::int64_t vat = 0;
};
// Applies the rules to a cart. Throws std::invalid_argument from line_cost.
inline PricedCart price_cart(const std::vector<CartLine>& lines, const std::string& coupon) {
PricedCart cart;
for (const CartLine& line : lines) {
const std::int64_t cost = line_cost(line);
cart.lines.push_back({line.name, line.quantity, cost});
cart.items += line.quantity;
cart.subtotal += cost;
}
if (!coupon.empty() && !is_known_coupon(coupon)) {
cart.unknown_coupon = coupon;
}
cart.discount = coupon_discount(coupon, cart.subtotal);
cart.total = cart.subtotal - cart.discount;
cart.vat = vat_included_in(cart.total);
return cart;
}
// Turns the numbers into the receipt text, in the same order as before.
inline std::string format_receipt(const PricedCart& cart) {
std::string out;
for (const PricedLine& line : cart.lines) {
out += line.name + " x" + std::to_string(line.quantity) + " " +
format_pence(line.cost) + "\n";
}
if (!cart.unknown_coupon.empty()) {
out += "Coupon " + cart.unknown_coupon + " not recognised\n";
}
out += "Items: " + std::to_string(cart.items) + "\n";
out += "Subtotal " + format_pence(cart.subtotal) + "\n";
if (cart.discount > 0) {
out += "Discount -" + format_pence(cart.discount) + "\n";
}
out += "Total " + format_pence(cart.total) + "\n";
out += "of which VAT " + format_pence(cart.vat) + "\n";
return out;
}
// The old entry point keeps its signature, so no caller changes.
inline std::string receipt(const std::vector<CartLine>& lines, const std::string& coupon) {
return format_receipt(price_cart(lines, coupon));
}
// [/snippet:priced]
} // namespace prc_refactor_receipt

The new tests check each rule on its own:

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

test_rules.cpp
// PRC-08 task 1: tests the refactoring made possible. Each rule is checked on
// its own, with numbers, instead of through the whole receipt text.
#include "lld_test.hpp"
#include "receipt.hpp"
#include <stdexcept>
using namespace prc_refactor_receipt;
LLD_TEST(format_pence_pads_the_pence) {
LLD_CHECK_EQ(format_pence(0), std::string("0.00"));
LLD_CHECK_EQ(format_pence(5), std::string("0.05"));
LLD_CHECK_EQ(format_pence(1205), std::string("12.05"));
LLD_CHECK_EQ(format_pence(1990), std::string("19.90"));
}
LLD_TEST(three_for_two_frees_one_item_per_group_of_three) {
LLD_CHECK_EQ(line_cost({"Tea", 100, 1}), 100);
LLD_CHECK_EQ(line_cost({"Tea", 100, 2}), 200);
LLD_CHECK_EQ(line_cost({"Tea", 100, 3}), 200);
LLD_CHECK_EQ(line_cost({"Tea", 100, 5}), 400);
LLD_CHECK_EQ(line_cost({"Tea", 100, 6}), 400);
LLD_CHECK_EQ(line_cost({"Free sample", 0, 4}), 0);
LLD_CHECK_THROWS(line_cost({"Tea", 100, 0}), std::invalid_argument);
LLD_CHECK_THROWS(line_cost({"Tea", -1, 1}), std::invalid_argument);
}
LLD_TEST(coupons_on_their_own) {
LLD_CHECK_EQ(coupon_discount("SAVE10", 1000), 100);
LLD_CHECK_EQ(coupon_discount("SAVE10", 9), 0);
LLD_CHECK_EQ(coupon_discount("FIVEOFF", 1999), 0);
LLD_CHECK_EQ(coupon_discount("FIVEOFF", 2000), 500);
LLD_CHECK_EQ(coupon_discount("", 5000), 0);
LLD_CHECK_EQ(coupon_discount("HALF", 5000), 0);
LLD_CHECK(is_known_coupon("FIVEOFF"));
LLD_CHECK(!is_known_coupon("save10"));
}
LLD_TEST(price_cart_gives_the_numbers_without_text) {
const PricedCart cart = price_cart({{"Biscuits", 120, 7}, {"Mug", 899, 1}}, "FIVEOFF");
LLD_CHECK_EQ(cart.items, 8);
LLD_CHECK_EQ(cart.subtotal, 1499);
LLD_CHECK_EQ(cart.discount, 0);
LLD_CHECK_EQ(cart.total, 1499);
LLD_CHECK_EQ(cart.vat, 249);
LLD_CHECK(cart.unknown_coupon.empty());
LLD_CHECK_EQ(price_cart({}, "HALF").unknown_coupon, std::string("HALF"));
}

Other valid solutions. Money could become its own type with an operator<< (see strong types); that is the better step if amounts start crossing many function boundaries. If the shop adds coupons every month, a table from code to rule would beat the if chain; with two coupons, the chain is easier to read. And if the email receipt never arrives, stopping after step 6 is fine: the rules have names and tests, and the split into numbers and text was only needed for a second layout.

When it is not worth doing. If the receipt is stable, nobody needs to test the rules alone, and no second layout is coming, a function of about 50 lines that exact-text tests already cover is not costing anything. Refactoring it “for cleanliness” is the step PRN-14 calls speculation in how to choose the next step.

Difficulty: moderate. Refactoring: introduce a seam. Tests: ctest -R prc_refactor_sensor.

A building’s heating system logs sensor readings to a text file, one id value per line. Two functions read it: one summarises each sensor, and one prints alarms for sensors over a limit. The parsing has several edge cases (comments, malformed lines, a reading equal to the limit), and each test today has to write a real file to the temporary directory, give it a name that cannot clash with another test program running at the same time, and remove it again. Make the parsing and the report testable from a string, without changing what either function does with a file.

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

readings.hpp
// PRC-08 task 2, start code. It works, and the characterization tests in
// tests/characterization.cpp pass, but the parsing rules can only be reached
// through a file on disk: summarize_sensor_file opens the file itself, and
// alarm_report opens it again through summarize_sensor_file. Every test has
// to write a real file first, and nothing can reuse the parsing for text that
// arrives another way.
#pragma once
#include <fstream>
#include <map>
#include <sstream>
#include <stdexcept>
#include <string>
namespace prc_refactor_sensor {
// What one sensor reported over the whole file.
struct SensorStats {
int count = 0;
double max = 0.0;
double total = 0.0;
};
// Every sensor found, by id (std::map keeps them sorted), and how many lines
// were skipped because they did not have the form "id value".
struct ReadingSummary {
std::map<std::string, SensorStats> sensors;
int skipped_lines = 0;
};
// Reads a file of readings, one "sensor-id value" per line. Blank lines and
// lines starting with '#' are comments. A line with a missing or non-numeric
// value, or with anything after the value, is counted as skipped. Throws
// std::runtime_error if the file cannot be opened.
inline ReadingSummary summarize_sensor_file(const std::string& path) {
std::ifstream file(path);
if (!file) {
throw std::runtime_error("cannot open readings file: " + path);
}
ReadingSummary summary;
std::string line;
while (std::getline(file, line)) {
if (line.empty() || line[0] == '#') {
continue;
}
std::istringstream fields(line);
std::string id;
double value = 0.0;
std::string extra;
// Read an id and a number; a third word means the line is malformed.
if (!(fields >> id >> value) || (fields >> extra)) {
++summary.skipped_lines;
continue;
}
// operator[] adds a zeroed SensorStats the first time an id is seen.
SensorStats& stats = summary.sensors[id];
if (stats.count == 0 || value > stats.max) {
stats.max = value;
}
++stats.count;
stats.total += value;
}
return summary;
}
// One line per sensor whose highest reading is above the limit, in id order,
// then a line saying how many lines were skipped, if any. Opens the file
// through summarize_sensor_file, so it throws what that throws.
inline std::string alarm_report(const std::string& path, double limit) {
const ReadingSummary summary = summarize_sensor_file(path);
std::ostringstream out;
int alarms = 0;
for (const auto& [id, stats] : summary.sensors) {
if (stats.max > limit) {
out << "ALARM " << id << " max " << stats.max << " over " << limit << '\n';
++alarms;
}
}
if (alarms == 0) {
out << "no alarms\n";
}
if (summary.skipped_lines > 0) {
out << "skipped " << summary.skipped_lines << " line(s)\n";
}
return out.str();
}
} // namespace prc_refactor_sensor

The six characterization tests cover two sensors, a negative first reading, comments and four kinds of malformed line, a missing file, a report with two alarms and a skipped line, and a reading exactly at the limit. All but the missing-file test write a small file first. Their helper class TempFile creates a file and removes it in its destructor, so the file goes even when a check fails.

Show the characterization tests for task 2

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

characterization.cpp
// PRC-08 task 2: characterization tests. The start code can only read a
// file, so each test writes one to the system's temporary directory and
// removes it afterwards. The same file is built against start/ and against
// solution/, and ctest may run both at once, so each file name gets a random
// number to keep the two programs from using the same file.
#include "lld_test.hpp"
#include "readings.hpp"
#include <filesystem>
#include <fstream>
#include <random>
#include <stdexcept>
#include <string>
using namespace prc_refactor_sensor;
namespace {
// Writes text to a new temporary file and deletes it when the object goes out
// of scope (RAII), even if a check in the middle of the test fails.
class TempFile {
public:
explicit TempFile(const std::string& text)
: path_(std::filesystem::temp_directory_path() /
("prc_refactor_sensor_" + std::to_string(std::random_device{}()) + ".txt")) {
std::ofstream(path_) << text;
}
~TempFile() {
std::error_code ignored; // the non-throwing overload: never throw from a destructor
std::filesystem::remove(path_, ignored);
}
TempFile(const TempFile&) = delete;
TempFile& operator=(const TempFile&) = delete;
std::string path() const { return path_.string(); }
private:
std::filesystem::path path_;
};
} // namespace
LLD_TEST(summarizes_each_sensor) {
const TempFile file("t1 21.5\nt2 19.25\nt1 23\nt1 20\n");
const ReadingSummary summary = summarize_sensor_file(file.path());
LLD_CHECK_EQ(summary.sensors.size(), 2u);
LLD_CHECK_EQ(summary.sensors.at("t1").count, 3);
LLD_CHECK_EQ(summary.sensors.at("t1").max, 23.0);
LLD_CHECK_EQ(summary.sensors.at("t1").total, 64.5);
LLD_CHECK_EQ(summary.sensors.at("t2").max, 19.25);
LLD_CHECK_EQ(summary.skipped_lines, 0);
}
LLD_TEST(the_first_reading_sets_the_max_even_when_negative) {
const TempFile file("freezer -18.5\nfreezer -20\n");
// Name the summary: a reference into a temporary would dangle.
const ReadingSummary summary = summarize_sensor_file(file.path());
LLD_CHECK_EQ(summary.sensors.at("freezer").max, -18.5);
}
LLD_TEST(skips_comments_and_counts_malformed_lines) {
// Only a '#' in the first column is a comment; " # x" has words, so it is
// read as id "#" and value "x", which is not a number.
const TempFile file("# kitchen\n\nt1 abc\nt1\nt1 20 extra\n # x\nt1 21\n");
const ReadingSummary summary = summarize_sensor_file(file.path());
LLD_CHECK_EQ(summary.skipped_lines, 4);
LLD_CHECK_EQ(summary.sensors.size(), 1u);
LLD_CHECK_EQ(summary.sensors.at("t1").count, 1);
}
LLD_TEST(a_missing_file_throws) {
LLD_CHECK_THROWS(summarize_sensor_file("/no/such/dir/readings.txt"), std::runtime_error);
LLD_CHECK_THROWS(alarm_report("/no/such/dir/readings.txt", 30.0), std::runtime_error);
}
LLD_TEST(reports_sensors_over_the_limit_in_id_order) {
const TempFile file("oven 230\nfridge 4.5\nboiler 81.5\nbad line here\n");
LLD_CHECK_EQ(alarm_report(file.path(), 80.0), std::string("ALARM boiler max 81.5 over 80\n"
"ALARM oven max 230 over 80\n"
"skipped 1 line(s)\n"));
}
LLD_TEST(a_reading_equal_to_the_limit_is_not_an_alarm) {
const TempFile file("oven 80\n");
LLD_CHECK_EQ(alarm_report(file.path(), 80.0), std::string("no alarms\n"));
}
  • summarize_sensor_file(path) and alarm_report(path, limit) keep their signatures, their results, and their std::runtime_error for a file that cannot be opened.
  • SensorStats and ReadingSummary keep their fields.
  • New functions may be added. The parsing rules must not change, even the odd one about a # that is not in the first column.
Show hints for task 2
  • A seam is a place where a test can supply something different without editing the code under test. What does the parsing need from the file? Only a way to read lines.
  • The standard library already has the type for “something to read lines from”: std::istream. Both std::ifstream and std::istringstream are one.
  • Keep the old functions. They can become two or three lines each that open the file and hand it on.
  • The report does not need to read anything at all, if it is given a summary.
Show the reference solution for task 2

The steps.

  1. Run the tests on the start code. All six pass.
  2. Extract summarize_readings(std::istream&). Move the loop, and everything in it, into the new function, unchanged; leave the opening and the check for a failed open in summarize_sensor_file, which now ends return summarize_readings(file);. As in TST-05’s first step, only where the input comes from changes, so the diff is easy to check by reading. Protected by: every characterization test, since they all still go through the file and then through the new function; and the missing-file test, which pins that the throw stayed in the wrapper.
  3. Extract format_alarms(const ReadingSummary&, double), and make alarm_report the two calls. Protected by: the two report tests, including “no alarms” at exactly the limit and the skipped-lines line.
  4. Write the tests the seam made possible, with string streams. Edge cases that each needed a file are now one line each: a line of spaces, no final newline, a Windows line ending, a number in exponent form. They all passed at once: they pin current behaviour, they did not find a bug. format_alarms is tested with a summary built by hand.

The result:

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

readings.hpp
// The seam: the rules, unchanged, reading from any input stream. The stream
// is borrowed: the caller owns it and must keep it alive during the call.
// Blank lines and lines starting with '#' are comments. A line with a missing
// or non-numeric value, or with anything after the value, is skipped.
inline ReadingSummary summarize_readings(std::istream& input) {
ReadingSummary summary;
std::string line;
while (std::getline(input, line)) {
if (line.empty() || line[0] == '#') {
continue;
}
std::istringstream fields(line);
std::string id;
double value = 0.0;
std::string extra;
// Read an id and a number; a third word means the line is malformed.
if (!(fields >> id >> value) || (fields >> extra)) {
++summary.skipped_lines;
continue;
}
// operator[] adds a zeroed SensorStats the first time an id is seen.
SensorStats& stats = summary.sensors[id];
if (stats.count == 0 || value > stats.max) {
stats.max = value;
}
++stats.count;
stats.total += value;
}
return summary;
}
// The old entry point: opens the file, then uses the seam. Throws
// std::runtime_error if the file cannot be opened, as before.
inline ReadingSummary summarize_sensor_file(const std::string& path) {
std::ifstream file(path);
if (!file) {
throw std::runtime_error("cannot open readings file: " + path);
}
return summarize_readings(file);
}

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

readings.hpp
// The report from a summary that already exists: no input at all. One line
// per sensor whose highest reading is above the limit, in id order, then a
// line saying how many lines were skipped, if any.
inline std::string format_alarms(const ReadingSummary& summary, double limit) {
std::ostringstream out;
int alarms = 0;
for (const auto& [id, stats] : summary.sensors) {
if (stats.max > limit) {
out << "ALARM " << id << " max " << stats.max << " over " << limit << '\n';
++alarms;
}
}
if (alarms == 0) {
out << "no alarms\n";
}
if (summary.skipped_lines > 0) {
out << "skipped " << summary.skipped_lines << " line(s)\n";
}
return out.str();
}
// The old entry point, now two calls. It throws what summarize_sensor_file
// throws.
inline std::string alarm_report(const std::string& path, double limit) {
return format_alarms(summarize_sensor_file(path), limit);
}

The stream is passed by reference and borrowed: summarize_readings reads from it during the call and keeps nothing, so the caller must keep the stream alive only for that call. The new tests:

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

test_streams.cpp
// PRC-08 task 2: tests the seam made possible. No files: the input is a
// string stream, and the report is checked from a summary built by hand.
#include "lld_test.hpp"
#include "readings.hpp"
#include <sstream>
#include <string>
using namespace prc_refactor_sensor;
namespace {
ReadingSummary summarize_text(const std::string& text) {
std::istringstream input(text); // lives until the call below returns
return summarize_readings(input);
}
} // namespace
LLD_TEST(reads_from_a_string_stream) {
const ReadingSummary summary = summarize_text("t1 21.5\nt2 19.25\nt1 23\n");
LLD_CHECK_EQ(summary.sensors.at("t1").count, 2);
LLD_CHECK_EQ(summary.sensors.at("t1").total, 44.5);
LLD_CHECK_EQ(summary.sensors.at("t2").max, 19.25);
}
LLD_TEST(edge_cases_are_cheap_to_list_now) {
// Each summary is named: LLD_CHECK_EQ keeps a reference to its argument,
// and a reference into a temporary summary would dangle.
const ReadingSummary empty = summarize_text("");
LLD_CHECK_EQ(empty.sensors.size(), 0u);
const ReadingSummary spaces = summarize_text(" \n"); // spaces only: no id
LLD_CHECK_EQ(spaces.skipped_lines, 1);
const ReadingSummary no_newline = summarize_text("t1 21"); // no final newline
LLD_CHECK_EQ(no_newline.sensors.at("t1").count, 1);
const ReadingSummary windows = summarize_text("t1 21\r\n"); // \r is whitespace to >>
LLD_CHECK_EQ(windows.skipped_lines, 0);
const ReadingSummary exponent = summarize_text("t1 1e2\n");
LLD_CHECK_EQ(exponent.sensors.at("t1").max, 100.0);
}
LLD_TEST(format_alarms_needs_no_input_at_all) {
ReadingSummary summary;
summary.sensors["oven"] = SensorStats{1, 230.0, 230.0};
summary.sensors["fridge"] = SensorStats{2, 4.5, 8.0};
LLD_CHECK_EQ(format_alarms(summary, 80.0), std::string("ALARM oven max 230 over 80\n"));
LLD_CHECK_EQ(format_alarms(summary, 300.0), std::string("no alarms\n"));
summary.skipped_lines = 2;
LLD_CHECK_EQ(format_alarms(summary, 300.0), std::string("no alarms\nskipped 2 line(s)\n"));
}

The tests name each summary before checking it. The test macro keeps a reference to its argument, and summarize_text("t1 21").sensors.at("t1") would be a reference into a temporary summary that is destroyed at the end of the line. The first version of these tests did that, and AddressSanitizer reported it as a heap-use-after-free.

Other valid solutions. The seam could be a callable that returns the next line, or an interface such as LineSource with one implementation per source. Both work, but std::istream is already that interface, and it costs nothing to use. A function that takes the whole text as a std::string is simpler still, if files are small; it reads everything into memory first. The lesson on seams compares these kinds.

When it is not worth doing. If the parser has one or two cases and temporary files are fast and reliable on every machine that runs the tests, file-based tests are fine. What is rarely worth it is the opposite extreme: a FileSystem interface, injected everywhere, to read one file. That is the speculative generality smell, and the std::istream parameter gives the same testability.

Difficulty: harder. Refactoring: replace manual new and delete with std::unique_ptr, keeping behaviour and improving exception safety. Tests: ctest -R prc_refactor_playlist.

A music app keeps a playlist of tracks. Callers hold const Track* pointers from find and add, and expect them to stay valid while other tracks are added or removed. The class owns its tracks through a std::vector<Track*> and deletes them by hand in four places. Two things are wrong, though no test shows them: add leaks a track if push_back throws, and copying a playlist compiles and deletes every track twice. Make ownership explicit and automatic, with no delete left, and keep everything callers rely on.

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

playlist.hpp
// PRC-08 task 3, start code. It works for the calls its characterization
// tests make, and they pass, but it owns its tracks through raw pointers and
// frees them by hand in four places. Two things are wrong with that:
// - If push_back in add() throws (it can, with std::bad_alloc), the new
// Track is leaked: nothing deletes it.
// - Copying or moving a Playlist compiles and copies the pointers, so two
// playlists delete the same tracks: a double delete, which is undefined
// behaviour. Nothing stops a caller from writing `Playlist b = a;`.
#pragma once
#include <cstddef>
#include <stdexcept>
#include <string>
#include <vector>
namespace prc_refactor_playlist {
struct Track {
std::string title;
int seconds = 0;
};
// An ordered list of tracks with unique titles. find() hands out pointers to
// tracks; a pointer stays valid until that track is removed or the playlist
// is cleared or destroyed, however many other tracks are added.
class Playlist {
public:
Playlist() = default;
~Playlist() {
for (Track* track : tracks_) {
delete track; // manual cleanup, place 1
}
}
// Adds a track at the end and returns a pointer to it. Throws
// std::invalid_argument for an empty title, a length below 1 second, or
// a title already in the list; the playlist is then unchanged.
const Track* add(const std::string& title, int seconds) {
Track* track = new Track{title, seconds};
if (title.empty() || seconds < 1) {
delete track; // manual cleanup, place 2
throw std::invalid_argument("a track needs a title and a length");
}
for (const Track* existing : tracks_) {
if (existing->title == title) {
delete track; // manual cleanup, place 2 again
throw std::invalid_argument("already in the playlist: " + title);
}
}
tracks_.push_back(track); // if this throws, track is leaked
return track;
}
// Removes the track with this title. Returns false if there is none.
bool remove(const std::string& title) {
for (auto it = tracks_.begin(); it != tracks_.end(); ++it) {
if ((*it)->title == title) {
delete *it; // manual cleanup, place 3
tracks_.erase(it);
return true;
}
}
return false;
}
void clear() {
for (Track* track : tracks_) {
delete track; // manual cleanup, place 4
}
tracks_.clear();
}
// The track with this title, or nullptr. The playlist keeps ownership.
const Track* find(const std::string& title) const {
for (const Track* track : tracks_) {
if (track->title == title) {
return track;
}
}
return nullptr;
}
std::size_t size() const { return tracks_.size(); }
int total_seconds() const {
int total = 0;
for (const Track* track : tracks_) {
total += track->seconds;
}
return total;
}
std::vector<std::string> titles() const {
std::vector<std::string> result;
for (const Track* track : tracks_) {
result.push_back(track->title);
}
return result;
}
private:
std::vector<Track*> tracks_; // owns every Track it points to
};
} // namespace prc_refactor_playlist

The double delete is real: a scratch program that copies a playlist, built against this header with AddressSanitizer, fails with a heap-use-after-free when the second copy is destroyed.

The characterization tests pin order, totals, refusals that leave the playlist unchanged, and that a pointer from find survives 100 more adds and a remove. They never copy a playlist.

Show the characterization tests for task 3

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

characterization.cpp
// PRC-08 task 3: characterization tests. They pin what callers can see:
// order, refusals, totals, and that a pointer from find() stays valid while
// other tracks come and go. They never copy a Playlist, because in the start
// code that is a double delete. The same file is built against start/ and
// against solution/; under AddressSanitizer a leak or double delete in any of
// these paths fails the run.
#include "lld_test.hpp"
#include "playlist.hpp"
#include <stdexcept>
#include <string>
#include <vector>
using namespace prc_refactor_playlist;
LLD_TEST(keeps_tracks_in_the_order_added) {
Playlist list;
list.add("Intro", 60);
list.add("Song", 200);
list.add("Outro", 45);
LLD_CHECK_EQ(list.size(), 3u);
LLD_CHECK_EQ(list.total_seconds(), 305);
LLD_CHECK(list.titles() == (std::vector<std::string>{"Intro", "Song", "Outro"}));
}
LLD_TEST(add_returns_the_same_track_that_find_returns) {
Playlist list;
const Track* added = list.add("Song", 200);
LLD_CHECK(added == list.find("Song"));
LLD_CHECK_EQ(added->seconds, 200);
LLD_CHECK(list.find("Missing") == nullptr);
}
LLD_TEST(refusals_leave_the_playlist_unchanged) {
Playlist list;
list.add("Song", 200);
LLD_CHECK_THROWS(list.add("", 10), std::invalid_argument);
LLD_CHECK_THROWS(list.add("Short", 0), std::invalid_argument);
LLD_CHECK_THROWS(list.add("Song", 99), std::invalid_argument);
LLD_CHECK_EQ(list.size(), 1u);
LLD_CHECK_EQ(list.find("Song")->seconds, 200); // not replaced by the duplicate
}
LLD_TEST(a_found_pointer_survives_other_adds_and_removes) {
Playlist list;
list.add("First", 10);
const Track* kept = list.add("Kept", 123);
for (int i = 0; i < 100; ++i) {
list.add("Filler " + std::to_string(i), 1); // the vector grows and moves its pointers
}
LLD_CHECK(list.remove("First"));
LLD_CHECK(kept == list.find("Kept"));
LLD_CHECK_EQ(kept->seconds, 123);
LLD_CHECK_EQ(kept->title, std::string("Kept"));
}
LLD_TEST(remove_and_clear) {
Playlist list;
list.add("A", 1);
list.add("B", 2);
list.add("C", 3);
LLD_CHECK(list.remove("B"));
LLD_CHECK(!list.remove("B"));
LLD_CHECK(list.titles() == (std::vector<std::string>{"A", "C"}));
list.clear();
LLD_CHECK_EQ(list.size(), 0u);
LLD_CHECK_EQ(list.total_seconds(), 0);
list.add("A", 5); // a cleared playlist can be used again, and titles are free again
LLD_CHECK_EQ(list.size(), 1u);
}
  • The public member functions keep their signatures and results, and find and add still return pointers that stay valid while other tracks come and go.
  • Copying a Playlist may stop compiling, and moving one may start to really move the tracks. In the start code both copy the pointers (it declares a destructor, so it gets no move operations) and end in a double delete, so no working code can depend on them. Those are the intended changes.
  • No new or delete in the result.
Show hints for task 3
  • std::unique_ptr<Track> owns one Track and deletes it when it is destroyed. A vector of them owns all the tracks.
  • The tempting simpler change, std::vector<Track>, breaks one of the tests. Which one, and why?
  • Deal with copying first, while the code still uses raw pointers. What does the compiler tell you when copying is deleted?
  • The checks in add do not need the new Track. What changes if they run before it is created?
  • After changing the member’s type, the compiler lists every line that needs to change.
Show the reference solution for task 3

The steps.

  1. Run the tests on the start code, including under asan-ubsan. All five pass, and the sanitizers report nothing: in the paths the tests take, the manual deletes are right.
  2. Delete the copy operations while the pointers are still raw: Playlist(const Playlist&) = delete; and the same for copy assignment. Protected by: the compiler. Any code that copied a playlist now fails to build and shows you where it is; the tests compile, so none of them copied.
  3. Move the checks in add above the allocation. The checks read only title, seconds, and the existing tracks, so reordering them changes no result. Both manual deletes in add disappear with it. Protected by: the refusal test, which checks each refusal throws and that a duplicate does not replace the original.
  4. Change the member to std::vector<std::unique_ptr<Track>> and fix what the compiler reports: add makes the track with std::make_unique, keeps a non-owning pointer from get(), then moves the owner into the vector; find returns get(); the loops take const auto&; remove and clear only erase, because destroying a unique_ptr deletes its track; the destructor goes. This step cannot be split: the member has one type or the other. Protected by: the compiler for every use of the member, all five tests for results, and AddressSanitizer for leaks and double deletes.
  5. Write the special members down, and test them. The copy stays deleted by hand. That is needed, not just tidy: without it a copy still fails to compile when someone tries it, but with a long error from inside std::vector, and std::is_copy_constructible_v still says true, because std::vector does not tell the type traits that its elements cannot be copied. The solution’s static_assert failed for exactly this reason before the lines were added. The moves are defaulted and noexcept, and a test checks that a moved playlist still hands out the same pointers.

The result:

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

playlist.hpp
// PRC-08 task 3, reference solution. The same Playlist, with the same
// behaviour for every call the characterization tests (start/tests) make,
// but each Track is owned by a std::unique_ptr, so no line deletes anything
// by hand. Two things changed on purpose, both only where the start code was
// broken:
// - add() can no longer leak: the checks run before anything is allocated,
// and the new Track is owned by a unique_ptr from the moment it exists.
// - Copying a Playlist no longer compiles (it was a double delete), and
// moving one now really moves the tracks. The copy is deleted by hand; see
// the comment above the special member functions for why.
#pragma once
#include <cstddef>
#include <memory>
#include <stdexcept>
#include <string>
#include <vector>
namespace prc_refactor_playlist {
struct Track {
std::string title;
int seconds = 0;
};
// An ordered list of tracks with unique titles. find() hands out pointers to
// tracks; a pointer stays valid until that track is removed or the playlist
// is cleared or destroyed, however many other tracks are added. Each Track
// lives in its own heap allocation for that reason: when the vector grows, it
// moves the unique_ptrs, not the Tracks they point to.
class Playlist {
public:
// [snippet:special]
// The destructor, and the moves, are the ones the compiler writes: they
// destroy or move the vector, and each unique_ptr deletes or hands over its
// Track. Copying is deleted by hand. A copy would not compile anyway, but
// only when someone tries it, with a long error from inside std::vector;
// and std::is_copy_constructible_v would still say true, because vector
// does not tell the type traits that its elements cannot be copied.
Playlist() = default;
Playlist(const Playlist&) = delete;
Playlist& operator=(const Playlist&) = delete;
Playlist(Playlist&&) noexcept = default;
Playlist& operator=(Playlist&&) noexcept = default;
~Playlist() = default;
// [/snippet:special]
// [snippet:add]
// Adds a track at the end and returns a pointer to it. Throws
// std::invalid_argument for an empty title, a length below 1 second, or
// a title already in the list; the playlist is then unchanged (the strong
// exception guarantee, now also when push_back throws).
const Track* add(const std::string& title, int seconds) {
if (title.empty() || seconds < 1) {
throw std::invalid_argument("a track needs a title and a length");
}
if (find(title) != nullptr) {
throw std::invalid_argument("already in the playlist: " + title);
}
auto track = std::make_unique<Track>(Track{title, seconds});
const Track* result = track.get(); // non-owning; the playlist owns it
// If push_back throws, `track` still owns the Track and frees it.
tracks_.push_back(std::move(track));
return result;
}
// [/snippet:add]
// Removes the track with this title. Returns false if there is none.
// erase destroys the unique_ptr, which deletes the Track.
bool remove(const std::string& title) {
for (auto it = tracks_.begin(); it != tracks_.end(); ++it) {
if ((*it)->title == title) {
tracks_.erase(it);
return true;
}
}
return false;
}
void clear() { tracks_.clear(); } // each unique_ptr deletes its Track
// The track with this title, or nullptr. The playlist keeps ownership.
const Track* find(const std::string& title) const {
for (const auto& track : tracks_) {
if (track->title == title) {
return track.get();
}
}
return nullptr;
}
std::size_t size() const { return tracks_.size(); }
int total_seconds() const {
int total = 0;
for (const auto& track : tracks_) {
total += track->seconds;
}
return total;
}
std::vector<std::string> titles() const {
std::vector<std::string> result;
for (const auto& track : tracks_) {
result.push_back(track->title);
}
return result;
}
private:
// [snippet:member]
// Owns every Track. Moving the vector moves the pointers, not the Tracks,
// so pointers from find() stay valid across a move of the Playlist.
std::vector<std::unique_ptr<Track>> tracks_;
// [/snippet:member]
};
} // namespace prc_refactor_playlist

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

test_ownership.cpp
// PRC-08 task 3: tests for what the refactoring changed on purpose. Copying
// is a compile error now (checked by static_assert, since a test cannot run
// code that does not compile), and a move keeps found pointers valid.
#include "lld_test.hpp"
#include "playlist.hpp"
#include <type_traits>
#include <utility>
using namespace prc_refactor_playlist;
static_assert(!std::is_copy_constructible_v<Playlist>);
static_assert(!std::is_copy_assignable_v<Playlist>);
static_assert(std::is_nothrow_move_constructible_v<Playlist>);
LLD_TEST(a_move_takes_the_tracks_and_keeps_pointers_valid) {
Playlist first;
const Track* song = first.add("Song", 200);
Playlist second = std::move(first);
LLD_CHECK(second.find("Song") == song); // the same Track, not a copy
LLD_CHECK_EQ(second.total_seconds(), 200);
first.clear(); // a moved-from Playlist is valid; clear() makes it empty for sure
LLD_CHECK_EQ(first.size(), 0u);
}
LLD_TEST(move_assignment_frees_the_old_tracks) {
// Under AddressSanitizer, a leaked "Old" Track would fail this run.
Playlist target;
target.add("Old", 1);
Playlist source;
source.add("New", 2);
target = std::move(source);
LLD_CHECK(target.find("Old") == nullptr);
LLD_CHECK(target.find("New") != nullptr);
}

What got better, exactly. In the start code, add gives no guarantee if push_back throws: the new track is leaked. In the solution, add gives the strong guarantee: if it throws, for a refusal or for std::bad_alloc, the playlist is unchanged and nothing leaks, because the unique_ptr still owns the track until the vector has taken it. The lesson on exception safety defines the guarantees. No test makes push_back fail, so this claim rests on reading the code, not on a test.

Why not std::vector<Track>? When a vector of values grows, it moves its elements to new memory, and every pointer from find dangles. A scratch copy of the solution changed to std::vector<Track> fails the pointer-survival test, and AddressSanitizer reports a heap-use-after-free when the test then reads through the old pointer. The heap allocation per track is the price of stable pointers.

Other valid solutions. A std::list<Track> also keeps pointers stable, with no smart pointer at all, at the cost of a node per track and slower walks. If callers do not need to keep pointers, a std::vector<Track> that returns copies, or an id to look a track up by, is simpler and faster; but that is a change of interface, and the tests would have to change with it. The lessons on smart pointers and RAII cover the alternatives.

When it is not worth doing. Rarely. Raw owning pointers cause undefined behaviour, not just harder changes. The one fair reason to wait is code that is being deleted soon; even then, deleting the copy operations (step 2) is two lines and removes the worst failure.

Task 4: replace a type code with std::variant

Section titled “Task 4: replace a type code with std::variant”

Difficulty: the hardest. Refactoring: replace a type code, and the switches on it, with std::variant. Tests: ctest -R prc_refactor_alerts.

A bank sends customers alerts: low balance, large payment, sign-in from a new device. Each alert is one Alert struct with an AlertKind and the fields of every kind, and three functions switch on the kind. The bank adds a new kind every few months, and each one has meant editing the struct, a factory, and all three switches, and checking that no function reads a field the kind does not set. Make each kind of alert one place in the code, so a new kind is one addition the compiler checks.

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

alerts.hpp
// PRC-08 task 4, start code. It works, and the characterization tests in
// tests/characterization.cpp pass, but each kind of alert is spread over
// five places: its fields in a struct shared by all kinds, its factory, and a
// switch in each of describe, priority, and channel. The bank adds a new
// kind of alert every few months, and each one means editing all of them.
// Nothing stops an Alert from carrying fields that do not belong to its kind.
#pragma once
#include <cstdint>
#include <stdexcept>
#include <string>
#include <utility>
namespace prc_refactor_alerts {
enum class AlertKind { low_balance, large_payment, new_device };
enum class Channel { email, sms, push };
// One struct for every kind; each field means something for one kind only.
struct Alert {
AlertKind kind = AlertKind::low_balance;
std::string account;
std::int64_t balance_pence = 0; // low_balance only
std::int64_t threshold_pence = 0; // low_balance only
std::int64_t amount_pence = 0; // large_payment only
std::string payee; // large_payment only
std::string device; // new_device only
std::string city; // new_device only
};
inline Alert low_balance_alert(std::string account, std::int64_t balance_pence,
std::int64_t threshold_pence) {
Alert alert;
alert.kind = AlertKind::low_balance;
alert.account = std::move(account);
alert.balance_pence = balance_pence;
alert.threshold_pence = threshold_pence;
return alert;
}
inline Alert large_payment_alert(std::string account, std::int64_t amount_pence,
std::string payee) {
Alert alert;
alert.kind = AlertKind::large_payment;
alert.account = std::move(account);
alert.amount_pence = amount_pence;
alert.payee = std::move(payee);
return alert;
}
inline Alert new_device_alert(std::string account, std::string device, std::string city) {
Alert alert;
alert.kind = AlertKind::new_device;
alert.account = std::move(account);
alert.device = std::move(device);
alert.city = std::move(city);
return alert;
}
// Whole pounds only: integer division drops the pence, rounding toward zero.
// -2050 becomes "-20", and -50 becomes "0".
inline std::string pounds(std::int64_t pence) { return std::to_string(pence / 100); }
inline std::string describe(const Alert& alert) {
switch (alert.kind) {
case AlertKind::low_balance:
return alert.account + ": balance " + pounds(alert.balance_pence) +
" is below " + pounds(alert.threshold_pence);
case AlertKind::large_payment:
return alert.account + ": payment of " + pounds(alert.amount_pence) + " to " +
alert.payee;
case AlertKind::new_device:
return alert.account + ": sign-in from " + alert.device + " in " + alert.city;
}
// Every enumerator returns above; this is reached only for a value cast
// into the enum by hand. The same two lines end every switch here.
throw std::logic_error("unknown alert kind");
}
// 1 is low, 3 is urgent.
inline int priority(const Alert& alert) {
switch (alert.kind) {
case AlertKind::low_balance:
return alert.balance_pence < 0 ? 3 : 2; // overdrawn is urgent
case AlertKind::large_payment:
return alert.amount_pence >= 100000 ? 3 : 1; // 1,000 pounds or more
case AlertKind::new_device:
return 3;
}
throw std::logic_error("unknown alert kind");
}
// Urgent alerts go by text message, whatever their kind. Others go the way
// their kind usually goes.
inline Channel channel(const Alert& alert) {
if (priority(alert) == 3) {
return Channel::sms;
}
switch (alert.kind) {
case AlertKind::low_balance:
return Channel::email;
case AlertKind::large_payment:
case AlertKind::new_device:
return Channel::push;
}
throw std::logic_error("unknown alert kind");
}
inline std::string channel_name(Channel channel) {
switch (channel) {
case Channel::email:
return "email";
case Channel::sms:
return "sms";
case Channel::push:
return "push";
}
throw std::logic_error("unknown channel");
}
} // namespace prc_refactor_alerts

The characterization tests use only the factories and the four free functions; they never touch the fields of an Alert. They pin each description, a rounding quirk (50 pence overdrawn shows as a balance of 0), the priority boundaries, the channel rule, and the channel names.

Show the characterization tests for task 4

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

characterization.cpp
// PRC-08 task 4: characterization tests. They use only what callers use:
// the three factory functions, describe, priority, channel, and
// channel_name. They never read or set the fields of an Alert, so the
// solution may change what an Alert is. The same file is built against
// start/ and against solution/.
#include "alerts.hpp"
#include "lld_test.hpp"
#include <string>
using namespace prc_refactor_alerts;
LLD_TEST(describes_each_kind) {
LLD_CHECK_EQ(describe(low_balance_alert("acc-1", 4210, 5000)),
std::string("acc-1: balance 42 is below 50"));
LLD_CHECK_EQ(describe(large_payment_alert("acc-2", 250000, "Garage Ltd")),
std::string("acc-2: payment of 2500 to Garage Ltd"));
LLD_CHECK_EQ(describe(new_device_alert("acc-3", "Pixel 9", "Leeds")),
std::string("acc-3: sign-in from Pixel 9 in Leeds"));
}
LLD_TEST(pounds_round_toward_zero_even_when_overdrawn) {
// Odd but current behaviour: 50 pence overdrawn shows as a balance of 0.
// A characterization test pins it; changing it is a separate decision.
LLD_CHECK_EQ(describe(low_balance_alert("acc-1", -50, 100)),
std::string("acc-1: balance 0 is below 1"));
LLD_CHECK_EQ(describe(low_balance_alert("acc-1", -2050, 0)),
std::string("acc-1: balance -20 is below 0"));
}
LLD_TEST(priority_rules) {
LLD_CHECK_EQ(priority(low_balance_alert("a", 0, 5000)), 2);
LLD_CHECK_EQ(priority(low_balance_alert("a", -1, 5000)), 3);
LLD_CHECK_EQ(priority(large_payment_alert("a", 99999, "x")), 1);
LLD_CHECK_EQ(priority(large_payment_alert("a", 100000, "x")), 3);
LLD_CHECK_EQ(priority(new_device_alert("a", "d", "c")), 3);
}
LLD_TEST(urgent_alerts_go_by_sms_and_others_by_their_usual_channel) {
LLD_CHECK(channel(low_balance_alert("a", 10, 5000)) == Channel::email);
LLD_CHECK(channel(low_balance_alert("a", -10, 5000)) == Channel::sms);
LLD_CHECK(channel(large_payment_alert("a", 5000, "x")) == Channel::push);
LLD_CHECK(channel(large_payment_alert("a", 200000, "x")) == Channel::sms);
LLD_CHECK(channel(new_device_alert("a", "d", "c")) == Channel::sms);
}
LLD_TEST(channel_names) {
LLD_CHECK_EQ(channel_name(Channel::email), std::string("email"));
LLD_CHECK_EQ(channel_name(Channel::sms), std::string("sms"));
LLD_CHECK_EQ(channel_name(Channel::push), std::string("push"));
}
  • The three factories, describe, priority, channel, and channel_name keep their signatures and results.
  • Alert may become a different type. The tests do not read its fields, so they still compile if it does.
  • The rounding quirk stays. Fixing it is a separate, later change.
Show hints for task 4
  • Give each kind its own struct with only its own fields. Then an Alert can be “one of these three”: that is std::variant.
  • std::visit calls a function with whichever alternative the variant holds. If each struct has a describe() member, one generic lambda, [](const auto& kind) { return kind.describe(); }, works for all.
  • One rule in channel is the same for every kind. Does it belong in each struct, or in one place?
  • A C++20 concept can say what every kind must provide, so that a new kind that forgets a rule is a compile error at the point where it is used.
Show the reference solution for task 4

The steps.

  1. Run the tests on the start code. All five pass.
  2. Add the three structs, unused: LowBalance, LargePayment, and NewDevice, each with its own fields and with describe, priority, and usual_channel members whose bodies are the matching case of each switch, copied, not rewritten. Protected by: nothing yet calls them, so the tests cannot fail; this step is checked by reading each body next to its case.
  3. Switch Alert to the variant. Replace the struct with using Alert = std::variant<LowBalance, LargePayment, NewDevice>;, make the factories return the structs, and make describe, priority, and channel call std::visit. This is the one large step, because Alert has one type or the other. Protected by: the compiler for every use of Alert’s old fields; the description tests for the copied text; the priority tests at 99,999 and 100,000 pence and on either side of 0; and the channel test.
  4. Keep the shared rule in one place. “Urgent alerts go by text message” is the same for every kind, so it stays in channel, before the visit, and each kind gives only its usual channel. Copying the rule into every struct would bring the duplication back. Protected by: the channel test, which checks an urgent alert of each kind.
  5. Delete what nothing uses any more: the AlertKind enum and the throw lines that ended the old switches. Then add the concept AlertKind (the name is free now), and constrain the visiting lambdas with it. A new kind that forgets a rule now fails with an error that names the concept. Protected by: the compiler, which would report any remaining use of the enum.
  6. Add the tests the split made possible: each kind’s rules without a variant, and that an alert holds exactly one kind.

The result:

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

alerts.hpp
// What every kind of alert must provide. A kind without one of these, or with
// the wrong return type, fails to compile where describe or priority visits it.
template <class T>
concept AlertKind = requires(const T& alert) {
{ alert.describe() } -> std::same_as<std::string>;
{ alert.priority() } -> std::same_as<int>; // 1 is low, 3 is urgent
{ alert.usual_channel() } -> std::same_as<Channel>;
};
struct LowBalance {
std::string account;
std::int64_t balance_pence = 0;
std::int64_t threshold_pence = 0;
std::string describe() const {
return account + ": balance " + pounds(balance_pence) + " is below " +
pounds(threshold_pence);
}
int priority() const { return balance_pence < 0 ? 3 : 2; } // overdrawn is urgent
Channel usual_channel() const { return Channel::email; }
};
struct LargePayment {
std::string account;
std::int64_t amount_pence = 0;
std::string payee;
std::string describe() const {
return account + ": payment of " + pounds(amount_pence) + " to " + payee;
}
int priority() const { return amount_pence >= 100000 ? 3 : 1; } // 1,000 pounds or more
Channel usual_channel() const { return Channel::push; }
};
struct NewDevice {
std::string account;
std::string device;
std::string city;
std::string describe() const { return account + ": sign-in from " + device + " in " + city; }
int priority() const { return 3; }
Channel usual_channel() const { return Channel::push; }
};
// An Alert holds exactly one of the kinds, by value, so it can no longer
// carry a field that does not belong to its kind.
using Alert = std::variant<LowBalance, LargePayment, NewDevice>;

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

alerts.hpp
// std::visit calls the lambda with whichever kind the Alert holds. The lambda
// is a template (its parameter is `auto`), constrained by the concept, so the
// compiler makes one copy of it per kind and checks each kind has the rule.
inline std::string describe(const Alert& alert) {
return std::visit([](const AlertKind auto& kind) { return kind.describe(); }, alert);
}
inline int priority(const Alert& alert) {
return std::visit([](const AlertKind auto& kind) { return kind.priority(); }, alert);
}
// The rule that is the same for every kind stays here, in one place: urgent
// alerts go by text message. Others go the way their kind usually goes.
inline Channel channel(const Alert& alert) {
if (priority(alert) == 3) {
return Channel::sms;
}
return std::visit([](const AlertKind auto& kind) { return kind.usual_channel(); }, alert);
}

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

test_kinds.cpp
// PRC-08 task 4: tests the refactoring made possible. Each kind is checked on
// its own, without going through a variant, and the type system now rules out
// alerts with fields from another kind.
#include "alerts.hpp"
#include "lld_test.hpp"
#include <string>
#include <variant>
using namespace prc_refactor_alerts;
static_assert(AlertKind<LowBalance> && AlertKind<LargePayment> && AlertKind<NewDevice>);
// A kind that forgets a rule does not satisfy the concept, so it could not be
// visited by describe, priority, or channel.
struct Unfinished {
std::string describe() const { return "?"; }
};
static_assert(!AlertKind<Unfinished>);
LLD_TEST(each_kind_on_its_own) {
const LowBalance low{"acc-1", -1, 5000};
LLD_CHECK_EQ(low.priority(), 3);
LLD_CHECK(low.usual_channel() == Channel::email);
const LargePayment payment{"acc-2", 99999, "x"};
LLD_CHECK_EQ(payment.priority(), 1);
LLD_CHECK(payment.usual_channel() == Channel::push);
}
LLD_TEST(an_alert_holds_exactly_one_kind) {
const Alert alert = large_payment_alert("acc-2", 5000, "Garage Ltd");
LLD_CHECK(std::holds_alternative<LargePayment>(alert));
LLD_CHECK_EQ(std::get<LargePayment>(alert).payee, std::string("Garage Ltd"));
LLD_CHECK(std::get_if<LowBalance>(&alert) == nullptr); // no balance to read by mistake
}

Adding a fourth kind is now one struct with its three rules, one name in the variant, and one factory, next to each other. If the struct is missing a rule, describe or priority does not compile. An alert also can no longer carry a payee and a city at once: each kind has only its own fields.

A more careful path for a large program. Here, step 3 changes Alert in one go because the only callers are the tests, and they do not read fields. In a large program where many callers read alert.payee, do it as a parallel change: add a function that converts the old struct to the variant, move the free functions onto the variant one by one, move the callers, and delete the old struct last. More steps, each one small.

Variant, interface, or switch? This solution organises the code by kind: each struct holds all the rules for its kind. That is right when kinds are added more often than operations, as here. The cost is the other direction: a new operation, such as “should this alert be batched?”, now means a member in every struct. If operations are added more often than kinds, the switch, or a std::visit with one lambda per kind in each function, keeps each operation in one place. A virtual interface (class Alert with describe() = 0) fits when kinds must be added without recompiling this code, for example by another team’s library; it costs a heap allocation per alert and pointer semantics. The lesson on run-time and compile-time polymorphism, and TST-05’s replace a conditional with polymorphism, weigh the same choice.

When it is not worth doing. With two kinds that have not changed in years, or with one switch in one function, the switch is easier to read than a variant and three structs. The refactoring pays when kinds keep arriving and the switches keep multiplying.

After each task, compare your steps with the reference, not only the final code:

  • Did every step leave the tests green? If a step went red and you debugged it, could it have been two smaller steps?
  • Did you edit a characterization test? If so, the behaviour changed, and that was not a refactoring.
  • For each step, can you name the test, or the compiler check, that would have caught a mistake in it? Where you cannot, did you add a test first, as in task 1, step 4?
  • Did you mix a fix into a refactoring? The case-sensitive coupons and the overdrawn rounding are tempting. TST-05’s common mistakes explains why they belong in a separate change.
  • Is your design different from the reference? That can be fine. If the same tests pass, the public interface is unchanged, and you can say what your design makes easier, it is a valid answer. The “other valid solutions” in each answer are real alternatives, not lesser ones.

This page checks nothing and records nothing: the tests in the examples are the only judge, and they run on your machine.

  • Refactoring changes structure, not behaviour. Characterization tests pin the behaviour first; then each small step is checked by them.
  • Before a step in a place the tests do not cover, add a test there first.
  • Extract function gives each rule a name and a test of its own (task 1).
  • A seam lets a test supply the input; often the standard library already has the right type, such as std::istream (task 2).
  • std::unique_ptr makes ownership automatic, removes manual cleanup, and can raise a function to the strong exception guarantee. Delete copy operations by hand when a member’s type traits would not (task 3).
  • std::variant with one struct per kind puts each kind in one place when kinds change often; a switch is still fine when they do not (task 4).
  • A refactoring is worth doing when it makes a change you actually need easier. Otherwise working code can stay as it is.