Refactoring safely in small steps
What you will learn on this page
Section titled “What you will learn on this page”- How to make the first change to code that has no tests, when there is nothing yet to check that change: a small seam, made by hand, that can be checked by reading.
- How to build a golden master: run the code over a grid of thousands of inputs, record every result, and compare every later version with the recording.
- How to choose the grid, and how to find out how strong it is, by making deliberate mistakes and counting what the recording notices.
- A sequence of named refactorings, each checked against the recording: introduce parameter object, extract function, replace conditional with polymorphism, and back again.
- Two steps that looked harmless and changed prices: one the recording caught at once, and one it caught only after a better grid.
- Why a bug fix is a separate step from a refactoring, and how to review the change it makes to the recording.
The problem
Section titled “The problem”A courier has priced parcels with the same function for years. The web shop, the counter app, and the nightly invoice run all call it, and nobody wants to touch it. Next quarter the courier adds a new service, and the team would like the function in a shape where that is a small change. First, though, they want to change its structure without changing a single price.
What the team knows about the rules, from reading the code:
- Weight. A parcel must weigh more than 0 kg and at most 30 kg; otherwise it cannot be sent.
- Carriage. Each zone has a price for the first kilogram and a price for each started kilogram after it.
- Service. Express costs 1.5 times as much; overnight costs twice as much, and does not go to zone 4, the islands.
- Handling. Fragile parcels cost 3.00 more; collection at the weekend costs 2.00 more.
- Fuel and membership. A fuel surcharge, in percent, is added to the price, and then members get 10% off.
- Minimum. The charge is at least 5.00, after any discount, and is rounded to the cent.
Here is the function:
VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// The courier's price for one parcel, as the code was found. This is the// code BEFORE any refactoring: the comments say what it does and where it is// hard to test or change; the code itself is left exactly as it was.//// Inputs: the zone (1 to 4, where 4 is the islands), the weight in kg, the// service as a bare number (0 standard, 1 express, 2 overnight), and two// yes/no flags. Result: the price in dollars, rounded to the cent, or -1// for "cannot be sent". There is no exception and no separate error type:// a caller must remember to compare the result with -1.//// Two more inputs are hidden inside the body, where no caller can see or// set them: today's day of the week, read from the system clock, and the// fuel surcharge, read from a global variable. Those two make it hard to// test, because a test cannot choose them.//// The rules run in a fixed order, top to bottom, and the order changes the// answer: weight, zone rate, extra kilograms, service, handling, fuel,// discount, minimum charge, rounding.double quote(int zone, double kg, int service, bool fragile, bool member) { // Refuse a weight of 0 or less, or over 30. Note what this lets through: // a NaN ("not a number") weight makes every comparison false, so it is // NOT refused here, and goes on to be priced. if (kg <= 0 || kg > 30) return -1; // Declared with no value; each branch of the if/else chain below gives // both a value, so neither is read before it is set. double price; double per_kg; // The zone rates: the price of the first kilogram and of each kilogram // after it. if (zone == 1) { price = 4.50; per_kg = 1.10; } else if (zone == 2) { price = 6.00; per_kg = 1.10; } else if (zone == 3) { price = 8.25; per_kg = 1.75; } else { // Every other zone number lands here, not only 4: zones 0, 5, or -7 // that do not exist are quietly priced as the islands. price = 12.00; per_kg = 1.75; } // std::ceil rounds up to a whole number, so 1.01 kg counts as 2 and // 7.5 kg as 8. Minus the first kilogram, that is 1 and 7 extra kilograms. if (kg > 1) price += (std::ceil(kg) - 1) * per_kg; // each started kg after the first // The service is a bare number: 1 and 2 are checked, and every other // number, including ones nobody meant such as 3 or -1, is standard. if (service == 1) { price *= 1.5; } else if (service == 2) { // Only zone 4 is refused. Zones 0 and 5 were priced as zone 4 above, // but get overnight service here, because this check names 4 alone. if (zone == 4) return -1; // no overnight service to the islands price *= 2; } if (fragile) price += 3.00; // Hidden input 1, the day. std::time(nullptr) reads the current time from // the system clock; std::localtime turns it into a local calendar date, a // std::tm, whose tm_wday is the day of the week, 0 Sunday to 6 Saturday. // A test cannot choose this day, so the same test can pass on a Tuesday // and fail on a Saturday. (std::localtime returns a pointer to one // object shared inside the C library, which the next call overwrites, // and a null pointer if it fails; this code does not check for that.) const std::time_t now = std::time(nullptr); const std::tm* local = std::localtime(&now); if (local->tm_wday == 0 || local->tm_wday == 6) price += 2.00; // weekend collection // Hidden input 2, the fuel surcharge: a global, set at startup. A test // can assign it, but every test then shares it. 12.5 means "add 12.5%", // so the price is multiplied by 1.125. price = price * (1 + g_fuel_surcharge_percent / 100); if (member) price = price * 0.9; // 10% off, after the fuel surcharge // The minimum comes after the discount, so a member's 4.05 becomes 5.00. if (price < 5.00) price = 5.00; // Round to the cent: times 100, round to the nearest whole number (a // half rounds away from zero), divide by 100. The answer is still a // double, so it is the closest double to the cent value, such as 25.87. return std::round(price * 100) / 100;}How this code works: One parcel through the legacy quote
The function is one long run from top to bottom. A local variable,
price, starts at the zone’s first-kilogram price, and each rule after
that changes it in place. There are two ways out early, each with
return -1: a bad weight, and overnight to zone 4. Everything else
reaches the last line.
Here is one parcel followed line by line: zone 2, 7.5 kg, express, fragile, a member, collected on a Saturday, with the global fuel surcharge set to 12.5. These are the same numbers as the unit test at the end of the page.
| Rule | What the code does | price after |
|---|---|---|
| Weight | 7.5 is neither 0 or less nor over 30 | not set yet |
| Zone rate | zone 2: first kg 6.00, each extra kg 1.10 | 6.00 |
| Extra kilograms | ceil(7.5) - 1 is 7, and 7 × 1.10 = 7.70 |
13.70 |
| Service | express: × 1.5 | 20.55 |
| Fragile | + 3.00 | 23.55 |
| Day, from the clock | Saturday is tm_wday 6: + 2.00 |
25.55 |
| Fuel, from a global | × (1 + 12.5 / 100), which is × 1.125 | 28.74375 |
| Member | × 0.9 | 25.869375 |
| Minimum | 25.869375 is not below 5.00 | 25.869375 |
| Rounding to the cent | × 100, round, ÷ 100 | 25.87 |
The numbers are worked in decimals; the computer’s double values can
differ from them in the last few digits, which does not change the cent
here.
Two rows of that table come from outside the argument list. Run the
same call on a Monday and the day row adds nothing, so the answer
changes; set the global to 0 and the fuel row changes it again. A test
calling quote(2, 7.5, 1, true, true) cannot say which answer is
right without knowing the day and the global, and it cannot choose
either one. That is the problem the next step solves.
It is not long, but it is hard to test, and hard to change:
- It has two hidden inputs. The day comes from the system clock,
and the fuel surcharge from a global that the program sets at
startup. A test can assign the global, but then every test shares
it, and the result depends on which test ran last. The clock can be
replaced only by tricks outside the code, such as linking a
different
timefunction. So a test that passes on a Tuesday may fail on a Saturday. - Its inputs are bare numbers.
serviceis 0, 1, or 2; any other number is quietly treated as standard. “Cannot be sent” is the price -1. - The order of the rules matters, and is written down only in the code. The minimum charge comes after the discount, so a member’s 4.05 becomes 5.00, not 4.50.
- It accepts things it should not. A zone that does not exist,
such as 0 or 5, is priced as zone 4, by the
elseat the end of the zone rates. Only overnight to zone 4 itself is refused, so overnight to 0 or 5 is priced too. That may be a bug, but some caller may rely on it.
Why the first step is the dangerous one
Section titled “Why the first step is the dangerous one”The safe way to refactor is to have a test that says what the code does, then change the code in small steps and run the test after each one. Here there is no test, and no good one can be written yet: a test could set the global, as shared state that every other test can change, but it could not set the day without replacing the system clock from outside the code. A small seam made by hand is cheaper and clearer than either trick.
So the first change has to be made without a net. The way to make it safe is to keep it as small and mechanical as possible, so that reading it is enough to check it:
- Change only where the inputs come from. Move the clock and the global out of the body and make them parameters. Do not rename anything, reformat anything, or fix anything on the way.
- Keep the old signature. It works out the day and reads the global, exactly as the body did, and passes them on. No caller changes, and the compiler checks that every call still matches.
- Let a reviewer check it by a diff. Inside the body, only the lines that read the clock and the global should differ.
This is step 1. Nothing else in the function changes:
VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// The seam: the same price function, but the two inputs it used to fetch// for itself, the day and the fuel surcharge, are now its last two// arguments, so a test can choose them.// The price in dollars, or -1 if the parcel cannot be sent.// service: 0 standard, 1 express, 2 overnight.// pickup_weekday: 0 Sunday ... 6 Saturday, as in std::tm. Only 0 and 6 mean// the weekend; any other number counts as a weekday.// fuel_surcharge_percent: 12.5 means "add 12.5%".double quote(int zone, double kg, int service, bool fragile, bool member, int pickup_weekday, double fuel_surcharge_percent);
// As before: today's day, and the global surcharge.// The old five-argument signature, kept so that no caller has to change.// Two functions with the same name and different parameter lists are// "overloads": the compiler picks the one whose arguments match the call,// so every existing five-argument call still compiles and reaches this one.double quote(int zone, double kg, int service, bool fragile, bool member);VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// The body of the legacy function, copied without a single change except// where it read the two hidden inputs; each of those places is marked// "Step 1" below. Every rule, every odd case (NaN weights, zones 0 and 5,// unknown service numbers), and the order of the rules stay as they were.double quote(int zone, double kg, int service, bool fragile, bool member, int pickup_weekday, double fuel_surcharge_percent) { if (kg <= 0 || kg > 30) return -1; double price; double per_kg; if (zone == 1) { price = 4.50; per_kg = 1.10; } else if (zone == 2) { price = 6.00; per_kg = 1.10; } else if (zone == 3) { price = 8.25; per_kg = 1.75; } else { price = 12.00; per_kg = 1.75; } if (kg > 1) price += (std::ceil(kg) - 1) * per_kg; // each started kg after the first if (service == 1) { price *= 1.5; } else if (service == 2) { if (zone == 4) return -1; // no overnight service to the islands price *= 2; } if (fragile) price += 3.00; // Step 1: the day is the argument, not the clock. The clock and the // std::localtime call moved, unchanged, into the old signature below. if (pickup_weekday == 0 || pickup_weekday == 6) price += 2.00; // weekend collection // Step 1: the surcharge is the argument, not the global. price = price * (1 + fuel_surcharge_percent / 100); if (member) price = price * 0.9; if (price < 5.00) price = 5.00; return std::round(price * 100) / 100;}
// The old signature. It does exactly what the old body did to find the two// hidden inputs, reads the clock and the global, and hands them to the// seven-argument version, so a caller gets the same price as before.double quote(int zone, double kg, int service, bool fragile, bool member) { const std::time_t now = std::time(nullptr); const std::tm* local = std::localtime(&now); return quote(zone, kg, service, fragile, member, local->tm_wday, g_fuel_surcharge_percent);}The new seven-argument function is the seam: a place where a test can supply what the code used to fetch for itself. It is not pretty, with seven bare arguments, but it does not need to be. It needs to be obviously the same as before, and it needs to make a test possible.
Recording a golden master
Section titled “Recording a golden master”A hand-worked test, as on the refactoring toward principles page, needs someone to work out each expected price. That works for a few cases. This function has six rules that interact, and the interesting cases are where they meet: a discount that takes a price below the minimum, a weight just over a kilogram, overnight to the islands. Working out enough of those by hand is slow, and the person doing it can make the same mistake as the code.
A golden master turns the question around. Instead of saying what the code should do, it records what the code does now, for many inputs, and checks that every later version does exactly the same. It is a characterization test at scale:
- Choose a grid of inputs. For each input, a short list of values; the grid is every combination.
- Write each result as one line of text, with the inputs in it, so a difference names the inputs that changed.
- Record the lines from the code as it is, read the recording, and keep it with the tests.
- After every step, produce the lines again and compare.
Here is the grid:
VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// Runs one version of the price function over every combination of the// values below, and returns one line of text per combination, always in// the same order.//// The argument `quote` is a function pointer (the QuoteFunction type in// golden.hpp): it names which version to run, such as v1::quote or// v4::quote, so the same grid can be run against every step. Each line// holds the inputs as well as the price, so when two runs disagree, the// differing line says which parcel changed.std::vector<std::string> quote_lines(QuoteFunction quote) { // The values to try for each input. Each is there to reach a rule or // an edge between rules; the page explains the choice of each. const int zones[] = {0, 1, 2, 3, 4, 5}; // 0 and 5 do not exist // A NaN, "not a number": a double that is not equal to anything, itself // included, and makes every ordered comparison such as < or > false. const double not_a_number = std::numeric_limits<double>::quiet_NaN(); const double weights[] = {0, 0.5, 1, 1.01, 7.5, 30, 30.01, // edges of the kg rules not_a_number}; // as std::stod("nan") gives // The service is passed as its number, 0, 1, or 2; this array gives the // name to print for each number: services[1] is "express". const char* const services[] = {"standard", "express", "overnight"}; const int days[] = {1, 6, 0}; // Monday, Saturday, Sunday // The name to print for a day number, so day_names[6] is "Sat". Only // days 0, 1, and 6 are used, so the other slots are left empty. const char* const day_names[] = {"Sun", "Mon", "", "", "", "", "Sat"}; const double fuel_surcharges[] = {0, 12.5};
// Seven nested loops, one per input, so every combination is visited: // 6 zones x 8 weights x 3 services x 2 x 2 x 3 days x 2 = 3,456 lines. // The innermost loop changes fastest, so lines come in pairs that differ // only in the fuel surcharge. {false, true} is a list written in place for // the loop to walk through, so each flag is tried both ways. std::vector<std::string> lines; for (const int zone : zones) { for (const double kg : weights) { for (int service = 0; service < 3; ++service) { for (const bool fragile : {false, true}) { for (const bool member : {false, true}) { for (const int day : days) { for (const double fuel : fuel_surcharges) { // Build one line, such as // "zone 2, 7.50 kg, express, fragile, member, Sat, // fuel 12.5%: 25.87", in a fixed-size buffer. // std::snprintf fills in each % placeholder in // turn from the arguments after the format: // %d a whole number, %.2f a number with two // decimals, %s a piece of text, %% a plain % // sign. It never writes more than `sizeof line` // bytes, so a line too long is cut short rather // than overflowing; real lines are about 70 // characters. The ?: picks ", fragile" or // nothing. The price comes from calling the // version under test, so a -1 refusal prints // "-1.00". A NaN weight prints as this C // library spells it, "nan". char line[160]; std::snprintf(line, sizeof line, "zone %d, %.2f kg, %s%s%s, %s, fuel %.1f%%: %.2f", zone, kg, services[service], fragile ? ", fragile" : "", member ? ", member" : "", day_names[day], fuel, quote(zone, kg, service, fragile, member, day, fuel)); // Copy the text into a new std::string at the end // of the vector; the buffer itself ends with this // pass of the loop. lines.emplace_back(line); } } } } } } } return lines;}How this code works: How the loops number the lines
The seven loops are nested like the wheels of a counter: the innermost one, the fuel surcharge, turns fastest, and the outermost one, the zone, turns slowest. Each pass through the innermost body prices one parcel and adds one line, so the lines always come out in the same order, and a line’s number says which inputs it holds.
Counting how many lines each loop’s step skips:
| Loop | Values | Lines per step of this loop |
|---|---|---|
| zone | 6 | 8 × 3 × 2 × 2 × 3 × 2 = 576 |
| weight | 8 | 3 × 2 × 2 × 3 × 2 = 72 |
| service | 3 | 2 × 2 × 3 × 2 = 24 |
| fragile | 2 | 2 × 3 × 2 = 12 |
| member | 2 | 3 × 2 = 6 |
| day | 3 | 2 |
| fuel | 2 | 1 |
A line’s number is 1 plus, for each loop, the position of its value in that loop’s list (counting from 0) times that loop’s step. Two lines quoted below, worked out this way:
- Line 649: zone 1 is position 1 (576), 0.5 kg is position 1 (72), and every other input is the first in its list (0). 576 + 72 + 1 = 649: “zone 1, 0.50 kg, standard, Mon, fuel 0.0%”.
- Line 1486: zone 2 (2 × 576 = 1,152), 7.5 kg at position 4 (4 × 72 = 288), express (24), fragile (12), member (6), Saturday at position 1 of the days (2), and 12.5% at position 1 of the surcharges (1). The sum is 1,485, plus 1, so line 1486.
The same sum puts the first NaN line, for zone 0, at line 505 (the NaN is position 7 of the weights: 7 × 72 = 504), which is where the failures later on this page begin.
Each list is chosen for a reason:
- Every value of each choice. All three services, fragile or not, member or not, both fuel surcharges in use.
- Both sides of every edge. For the weight rule: 0 and 30.01, which are refused, and 30, which is not. For the “each started kilogram” rule: 1, which has no extra kilogram, and 1.01, which has one. For the weekend rule: Monday, and both days of the weekend, since the code checks each separately.
- The odd inputs the code accepts. Zones 0 and 5 do not exist, but the code prices them, so the recording must say how. A NaN weight is in the list for a reason that the next sections show; the first version of this grid did not have it.
The grid has 6 zones × 8 weights × 3 services × 2 × 2 × 3 days × 2 fuel surcharges = 3,456 lines. The test compares every line, and reports the first three that differ, with their line numbers:
VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
namespace {// Compares every line with the recording, and reports the first three that// differ, with their line numbers, so a failure says which inputs changed.// LLD_CHECK_EQ(a, b) and report_failure (lld_test.hpp) log a failure and go on.void check_against_recording(QuoteFunction quote, const std::string& file) { const std::vector<std::string> actual = quote_lines(quote); // what this version prints const std::vector<std::string> recorded = read_lines(std::string(GOLDEN_DIR) + "/" + file); LLD_CHECK_EQ(actual.size(), recorded.size()); // as many lines as recorded? std::size_t differing = 0; // how many lines do not match for (std::size_t i = 0; i < actual.size() && i < recorded.size(); ++i) { // in range of both if (actual[i] == recorded[i]) continue; // same: on to the next line if (++differing <= 3) { // count it; print only the first three lld::test::report_failure(__FILE__, __LINE__, // file and line of this call file + " line " + std::to_string(i + 1) + ": got \"" + actual[i] + "\", recorded \"" + recorded[i] + "\""); } } LLD_CHECK_EQ(differing, std::size_t{0}); // the verdict: no line may differ}
} // namespace
// LLD_TEST(name) { ... } defines one test, which the site's small test// runner finds and runs; a test passes if none of its checks failed.//// Steps 1 to 4 are refactorings, so each must print exactly the lines// recorded from step 1. Passing v1::quote as a QuoteFunction picks the// seven-argument overload, the one whose parameters match that pointer type.LLD_TEST(every_refactoring_step_prints_what_step_1_printed) { check_against_recording(v1::quote, "golden_quotes.txt"); check_against_recording(v2::quote, "golden_quotes.txt"); check_against_recording(v3::quote, "golden_quotes.txt"); check_against_recording(v4::quote, "golden_quotes.txt");}
// Step 5 changes behaviour on purpose, so it is compared with its own// recording, made after its differences from the old one were reviewed.LLD_TEST(the_zone_fix_changes_only_what_it_was_meant_to) { check_against_recording(v5::quote, "golden_quotes_v5.txt");}How this code works: check_against_recording
- Produce and load.
quote_lines(quote)runs the version under test over the grid;read_linesloads the recorded file, one string per line. If the file cannot be opened,read_linesthrowsstd::runtime_error, which ends the test, and the test runner reports it as an unexpected exception. - Same length. The first
LLD_CHECK_EQfails if the two lists have different lengths. Like every check here, a failure is recorded and the test goes on, so the line comparison still runs. - Line by line. The loop compares line
iof each list, and stops at the end of the shorter one, so it never reads past either. Matching lines are skipped withcontinue. Each differing line adds 1 todiffering;++differingadds first and then compares, so the first three differences, and only those, are printed withreport_failure. The line number printed isi + 1, becauseicounts from 0 and a text editor counts lines from 1. - The verdict. The last check fails unless
differingis 0, and prints the count.std::size_t{0}is a zero of the same type asdiffering, so the two sides of the comparison match.
Every failure message starts with the file and line where the check
sits, from __FILE__ and __LINE__. That is why, in the outputs below,
the three differences all say test_golden.cpp:39 (the
report_failure call) and the count says test_golden.cpp:44 (the last
check).
A recording is checked by reading it, not trusted. It records the code’s behaviour, bugs included, but someone still has to look at it, or it may record a crash value or a mistake in the test that nobody noticed. Here that meant checking a sample of lines by hand against the rules, including line 649, a 4.50 parcel raised to the minimum:
zone 1, 0.50 kg, standard, Mon, fuel 0.0%: 5.00and line 1486, worked out step by step in the unit tests later on this page:
zone 2, 7.50 kg, express, fragile, member, Sat, fuel 12.5%: 25.87It also meant looking at the shape of the whole file: 1,008 lines say -1.00, the ones for 0 kg, for 30.01 kg, and for overnight to zone 4, which is the number those three rules should give.
How strong is the net?
Section titled “How strong is the net?”A recording that passes says only that the code did the same on these inputs. To find out what kinds of change it would notice, a scratch copy of step 1 was given one deliberate mistake at a time, recorded, and compared with the recording:
| Deliberate mistake in step 1 | Lines that differ, of 3,456 |
|---|---|
| Express costs 1.45 times, not 1.5 | 864 |
| Weekend means Sunday only | 816 |
Overnight refused from zone 3 up, zone >= 3 |
288 |
| Zone 2 charges 1.15 per extra kg, not 1.10 | 216 |
30 kg refused, kg >= 30 for kg > 30 |
408 |
std::round for std::ceil on the weight |
408 |
| The minimum charge is 4.99 | 9 |
| The minimum applied before the discount | 6 |
kg >= 1 for kg > 1 before the extra kg |
0 |
Three rows say more than the others:
- The minimum charge is reached by only 9 lines. Almost every parcel costs more than 5.00. A recording of 3,456 lines still guards this rule with a handful, all from zone 1 at a kilogram or less, or with a NaN weight, which is priced as one kilogram. That is enough to catch these two mistakes, but it is thin, and the rule deserves its own unit tests as soon as it has a name.
- Rounding the weight is told apart from ceiling it by one weight only. Of the eight weights, only 1.01 gives a different answer: 7.5 rounds and ceils to the same 8. A weight such as 7.2 would add a second witness. Each value in the grid should be there to tell something apart.
- 0 lines is the right answer for the last row. At exactly 1 kg,
the extra charge is
(ceil(1) - 1) × rate, which is 0, so the two conditions give the same price for every input. That mistake does not change behaviour, and nothing could catch it. Mutation testing calls such a change an equivalent mutant. When a deliberate mistake passes, the first question is whether it changed anything.
This is a small version of mutation testing, which does the same automatically, and at scale: it makes many such changes to the code and reports the ones that no test notices.
Step 2: parameter objects and named rules
Section titled “Step 2: parameter objects and named rules”With a net in place, the real refactoring can start. Step 2 is a group of small refactorings, each of which keeps every price. Introduce parameter object and extract function are names from the refactoring literature; the other two are described by what they do:
- Introduce parameter object. The seven arguments become two
structs:
Parcel, what is being sent, andQuoteTerms, what the price depends on besides the parcel. - Replace a type code with an enum.
servicebecomesenum class Service, and the day becomes astd::chrono::weekday, so a caller cannot pass a day as a service. - Replace a special value with an optional. “Cannot be sent” is
std::nullopt, not the price -1. - Extract function, once for each rule, in the order the old body applied them.
VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// The service as a named type instead of the bare numbers 0, 1, and 2.// `enum class` keeps the names inside the type (Service::express) and will// not turn into an int, or be made from one, without a cast, so a day or a// zone cannot be passed where a service is wanted.enum class Service { standard, express, overnight };
// A parameter object: what is being sent, grouped in one struct instead of// four separate arguments. It can be written member by member in braces,// in declaration order: Parcel{2, 7.5, Service::express, true}. Each member// has a default (the `= ...`), used for any member the braces leave out.struct Parcel { int zone = 1; // 1 to 4; zone 4 is the islands double kg = 0; Service service = Service::standard; bool fragile = false;};
// What the price depends on besides the parcel.// The second parameter object, for the two inputs that used to be hidden// (the day and the surcharge) and the membership.struct QuoteTerms { // A day of the week from the standard library, such as // std::chrono::Saturday, rather than an int that could mean anything. // It has no default written here, so give it one every time. std::chrono::weekday pickup_day; double fuel_surcharge_percent = 0; bool member = false;};
// The price in dollars, or std::nullopt if the parcel cannot be sent.// std::optional<double> either holds a price or holds nothing, so "cannot// be sent" is no longer a price of -1 that a caller might add up by mistake.// Both arguments are passed by const reference: read, not copied or changed.std::optional<double> quote(const Parcel& parcel, const QuoteTerms& terms);VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// Each rule of the old body, pulled out into a function of its own with a// name (the "extract function" refactoring), in the order the old body ran// them. Every rule computes exactly what the old lines did, odd cases// included; quote() at the end calls them in that order.
// namespace { ... } with no name: what is inside is private to this file.namespace {
// The two prices that make up a zone's rate, given names instead of the// two loose variables the old code set in each branch.struct ZoneRate { double first_kg; double each_extra_kg;};
// Any zone but 1 to 3 is charged as zone 4, as it always has been.// `return {4.50, 1.10};` builds a ZoneRate from its two members, in order.ZoneRate zone_rate(int zone) { switch (zone) { case 1: return {4.50, 1.10}; case 2: return {6.00, 1.10}; case 3: return {8.25, 1.75}; default: return {12.00, 1.75}; // zone 4, and also 0, 5, -7, ... }}
} // namespace
// The old check, negated as a whole. A NaN weight fails every comparison,// so the old code let it through, and so does this, until step 5.// True if the parcel's weight can be accepted. The ! ("not") is applied to// the old refusal condition as a whole, so this is true exactly when the// old code did not return -1 for the weight, NaN included.bool can_carry(double kg) { return !(kg <= 0 || kg > 30); }
// The price of carrying the parcel to its zone, before any service,// handling, fuel, or discount: the first kilogram, plus each started// kilogram after it. A NaN weight makes `kg > 1` false, so it pays the// first kilogram only.double carriage(int zone, double kg) { const ZoneRate rate = zone_rate(zone); double price = rate.first_kg; if (kg > 1) price += (std::ceil(kg) - 1) * rate.each_extra_kg; // each started kg after the first return price;}
// The price with the service applied, or std::nullopt if that service does// not go to `zone`. Returning a plain double, as in `return price;`, puts it// into the optional, which then holds a price.std::optional<double> with_service(double price, Service service, int zone) { switch (service) { case Service::standard: return price; case Service::express: return price * 1.5; case Service::overnight: if (zone == 4) return std::nullopt; // no overnight service to the islands return price * 2; } // Compilers warn if a function could reach its end without a return, and // cannot be sure that `service` holds one of the three names (a cast // could put another number in it), so this line is there for them. return std::nullopt; // not reached: every Service is handled above}
// The two handling surcharges: 3.00 for a fragile parcel, 2.00 for// collection on a Saturday or a Sunday. `price` is a copy of the caller's// value (passed by value), so changing it here changes nothing outside.double with_handling(double price, bool fragile, std::chrono::weekday pickup_day) { if (fragile) price += 3.00; if (pickup_day == std::chrono::Saturday || pickup_day == std::chrono::Sunday) { price += 2.00; // weekend collection } return price;}
// The fuel surcharge first, then the member's 10% off, as two separate// multiplications in that order. The page shows why merging them into one// factor would change some prices by a cent.double with_fuel_and_discount(double price, double fuel_surcharge_percent, bool member) { price = price * (1 + fuel_surcharge_percent / 100); if (member) price = price * 0.9; return price;}
// The amount actually charged: at least 5.00, rounded to the cent.double to_charge(double price) { if (price < 5.00) price = 5.00; // the minimum charge, after any discount return std::round(price * 100) / 100;}
// The whole price, built from the rules in the old order. Each step hands// its result to the next. Two steps can refuse the parcel, and each refusal// returns std::nullopt at once, so nothing after it runs.std::optional<double> quote(const Parcel& parcel, const QuoteTerms& terms) { if (!can_carry(parcel.kg)) return std::nullopt; // refusal 1: the weight // The inner call runs first: carriage for the zone and weight, then the // service applied to that price. const std::optional<double> carried = with_service(carriage(parcel.zone, parcel.kg), parcel.service, parcel.zone); // An empty optional converts to false: refusal 2, overnight to zone 4. if (!carried) return std::nullopt; // *carried takes the price out of the optional; it is safe here because // the line above has just made sure the optional holds one. const double handled = with_handling(*carried, parcel.fragile, terms.pickup_day); // Fuel and discount, then the minimum and rounding. The double that // to_charge returns is turned into an optional holding that price. return to_charge(with_fuel_and_discount(handled, terms.fuel_surcharge_percent, terms.member));}How this code works: The new quote, rule by rule
quote(Parcel, QuoteTerms) does what the old body did, but each rule
is now a call, and each call’s result is handed to the next. Following
the same parcel as before (zone 2, 7.5 kg, express, fragile, collected
on a Saturday, a member, fuel 12.5%):
can_carry(7.5)is true, so the parcel is not refused.carriage(2, 7.5)looks up zone 2’s rate,{6.00, 1.10}, and returns 6.00 + 7 × 1.10 = 13.70.with_service(13.70, Service::express, 2)returns an optional holding 20.55. For overnight to zone 4 it would hold nothing, andif (!carried)would returnstd::nulloptat once.*carriedtakes the 20.55 out of the optional.with_handlingadds 3.00 for fragile and 2.00 for Saturday: 25.55.with_fuel_and_discount(25.55, 12.5, true)multiplies by 1.125, then by 0.9: 25.869375.to_charge(25.869375)leaves it, as it is above 5.00, and rounds it to 25.87, whichquotereturns inside an optional.
Each rule now has a name and can be called alone, which is what makes the unit tests at the end of the page possible. The rules take plain values and return plain values; none of them reads the clock or a global, so the same call always gives the same answer.
The old interfaces stay, built on the new one, so no caller has to move yet; the golden master calls the seven-argument one for every version, which keeps the comparison fair:
VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
namespace {
// The old code treated every number but 1 and 2 as standard.// Turns the old service number into the enum, keeping that behaviour: 3 or// -1 still become Service::standard, so the prices stay the same.Service to_service(int service) { if (service == 1) return Service::express; if (service == 2) return Service::overnight; return Service::standard;}
} // namespace
// Step 1's seven-argument seam, now a thin adapter: it converts the old// bare arguments into the two parameter objects, calls the new quote, and// converts the answer back to the old form. The golden master calls this// one for every version, so every version is compared in the same way.double quote(int zone, double kg, int service, bool fragile, bool member, int pickup_weekday, double fuel_surcharge_percent) { // Braces fill the members in the order they are declared in Parcel. const Parcel parcel{zone, kg, to_service(service), fragile}; // std::chrono::weekday is made from an unsigned number, so the int is // converted first with static_cast. 0 is Sunday and 6 Saturday, as in // tm_wday; but 7 also means Sunday here, where step 1 saw a weekday // (the page explains why that is safe for the real callers). const QuoteTerms terms{std::chrono::weekday(static_cast<unsigned>(pickup_weekday)), fuel_surcharge_percent, member}; // value_or(-1): the price if the optional holds one, otherwise -1, the // old "cannot be sent" answer. return quote(parcel, terms).value_or(-1);}That conversion keeps every price only for days 0 to 6, which is what
tm_wday gives. std::chrono::weekday treats 7 as Sunday, so a
fragile 1 kg parcel to zone 1, standard, picked up on “day 7”
with no fuel surcharge, costs 7.50 in step 1, which saw no weekend, and 9.50 in step 2. The grid holds only days 0, 1, and 6,
so the golden master cannot see this. It is safe because the only
callers pass tm_wday; that is worth a comment on the seam, and it
is another input nobody should send.
In this example the refactorings are kept together in one version, to keep the number of versions small. In real work each is a separate change, with the golden master run after each, which takes a few hundredths of a second here. When one fails, there is only one small change to look at.
Text description of the diagram
Two parts, before and after. Before: a single box, quote with seven arguments (zone, kg, service, fragile, member, weekday, fuel), which holds the weight check, the zone rates, the extra kilograms, the service, the handling, the fuel, the discount, the minimum, and the rounding, and returns -1 if the parcel is refused. After: the old quote with five arguments and the step 1 seam with seven convert their arguments and have a dashed arrow labelled “calls” to a new quote taking a Parcel and a QuoteTerms, which returns an optional price. The new quote has dashed “calls” arrows to six functions: can_carry, carriage, with_service, with_handling, with_fuel_and_discount, and to_charge. A flow arrow from the Before group to the After group shows the step.
Diagram source (Mermaid)
flowchart TB
subgraph Before
B1["quote(zone, kg, service, fragile,<br/>member, weekday, fuel)<br/>weight check, zone rates, extra kg,<br/>service, handling, fuel, discount,<br/>minimum, rounding; -1 if refused"]
end
subgraph After
A0["old quote(5 arguments) and<br/>step 1 seam (7 arguments)<br/>convert, call the new one"] -.->|calls| A1["quote(Parcel, QuoteTerms)<br/>optional price"]
A1 -.->|calls| A2["can_carry"]
A1 -.->|calls| A3["carriage"]
A1 -.->|calls| A4["with_service"]
A1 -.->|calls| A5["with_handling"]
A1 -.->|calls| A6["with_fuel_and_discount"]
A1 -.->|calls| A7["to_charge"]
end
Before --> AfterTwo parts of this step changed prices on the first try. Both looked like refactorings.
A tidier condition that was not the same
Section titled “A tidier condition that was not the same”The old weight check refuses a parcel when kg <= 0 || kg > 30. A
function called can_carry should say when a parcel is accepted, so
the first version of it turned the condition around, flipping each
comparison. This compiled with both compilers, and its golden master
passed:
// The first try at step 2's can_carry: the old refusal test,// `kg <= 0 || kg > 30`, turned around by flipping each comparison.// For every ordinary number it agrees with the old code. For a NaN weight// both comparisons are false, so this returns false and refuses the// parcel, where the old code let it through and priced it.bool can_carry(double kg) { return kg > 0 && kg <= 30; }At that point the grid had seven weights, and no NaN, so 3,024 lines.
All of them matched. The question that found the difference came from
reading the change. De Morgan’s law, that !(a || b) is !a && !b,
always holds. The step after it does not: writing kg > 0 for
!(kg <= 0) is right for every number, but not for a NaN, which is
not a number. With a NaN, == and every ordered comparison, such as
<= and >, are false, and != is true. So kg <= 0 and kg > 0
are both false. The old check,
NaN <= 0 || NaN > 30, is false, so the old code does not refuse a NaN
weight. It goes on, finds NaN > 1 false too, and charges for one
kilogram. The new check, NaN > 0 && NaN <= 30, is also false, so the
new code refuses it.
Could a NaN weight reach this function? If any caller parses a weight
from text with std::stod, then yes: std::stod accepts the text
“nan”. So a NaN joined the grid, step 1 was recorded again, and the
golden master was run against the new can_carry. The first three
failures and the count:
tests/test_golden.cpp:39: check failed: golden_quotes.txt line 505: got "zone 0, nan kg, standard, Mon, fuel 0.0%: -1.00", recorded "zone 0, nan kg, standard, Mon, fuel 0.0%: 12.00"tests/test_golden.cpp:39: check failed: golden_quotes.txt line 506: got "zone 0, nan kg, standard, Mon, fuel 12.5%: -1.00", recorded "zone 0, nan kg, standard, Mon, fuel 12.5%: 13.50"tests/test_golden.cpp:39: check failed: golden_quotes.txt line 507: got "zone 0, nan kg, standard, Sat, fuel 0.0%: -1.00", recorded "zone 0, nan kg, standard, Sat, fuel 0.0%: 14.00" actual: 408 expected: 0tests/test_golden.cpp:44: check failed: differing == std::size_t{0}That is the output for step 2; steps 3 and 4, which had the same
check, failed the same way. 408 parcels that used to be priced were
now refused. Refusing a NaN weight is surely right, but it is a change
of behaviour, and a refactoring is not the place for one. So
can_carry went back to the old condition, negated as a whole, with a
comment saying why, as the rules code above shows, and refusing a NaN
became part of the behaviour change in step 5.
Two lessons came out of this. The grid is only as good as its values, and the values come from thinking about what the code can be given, not only about what it is meant to be given. And a passing golden master does not replace reading the change: here, reading found the question, and the grid then answered it.
One multiplication instead of two
Section titled “One multiplication instead of two”The fuel surcharge and the discount are both factors, so it is tempting to multiply them first and apply them once. A scratch copy of step 2 did that. It compiled without warnings with both compilers:
In arithmetic, (p × f) × d and p × (f × d) are equal. In double
arithmetic, each multiplication rounds its result to the nearest value
a double can hold, so the two orders can differ in the last bit. The
first three failures and the count, the same with both compilers:
tests/test_golden.cpp:39: check failed: golden_quotes.txt line 104: got "zone 0, 0.50 kg, express, member, Mon, fuel 12.5%: 18.22", recorded "zone 0, 0.50 kg, express, member, Mon, fuel 12.5%: 18.23"tests/test_golden.cpp:39: check failed: golden_quotes.txt line 176: got "zone 0, 1.00 kg, express, member, Mon, fuel 12.5%: 18.22", recorded "zone 0, 1.00 kg, express, member, Mon, fuel 12.5%: 18.23"tests/test_golden.cpp:39: check failed: golden_quotes.txt line 536: got "zone 0, nan kg, express, member, Mon, fuel 12.5%: 18.22", recorded "zone 0, nan kg, express, member, Mon, fuel 12.5%: 18.23" actual: 15 expected: 0tests/test_golden.cpp:44: check failed: differing == std::size_t{0}All 15 differing lines were for members with the 12.5% surcharge, and
each was one cent cheaper. On line 104 the exact price is 18.00 × 1.125
× 0.9 = 18.225, exactly half a cent. Neither order computes it
exactly: the old order gives the double 18.225000000000001, which
rounds up to 18.23, and the merged factor gives 18.224999999999998,
which rounds down to 18.22.
One cent on 15 inputs in 3,456 is exactly the kind of difference that
reading the code would never find and a few hand-worked tests would
very likely miss. It matters anyway: an invoice that disagrees with the
quote by a cent is a support call. The step was not taken. The real
fix for money in double is to compute in whole cents, which
property-based and table-driven tests
does for a shared bill, and changing to cents would change some
prices, so it would be a behaviour change of its own, planned and
announced like step 5.
A second scratch change added the two handling surcharges together
first, then added the sum once. On this grid, no line differed. That
is evidence that it is safe on these inputs, not proof: addition of
double values is not associative either.
Step 3: replace a conditional with polymorphism
Section titled “Step 3: replace a conditional with polymorphism”The switch on Service in with_service is the part that will
grow, since the new service is coming. A common refactoring replaces a
switch on a type code with a class for each case and a virtual call:
VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// What a service level does to the price of carriage.// The interface of step 3's "replace conditional with polymorphism": one// class per case of the old switch, each with its own apply. A caller holds// a `const ServiceLevel&` and calls apply without knowing which service it// has; the virtual call runs the version of the actual object.class ServiceLevel {public: // A virtual destructor, as every base class meant to be used through a // pointer or reference should have, so destroying a derived object // through the base runs the derived destructor too. virtual ~ServiceLevel() = default; // The price with this service, or std::nullopt if it does not go to `zone`. // `= 0` makes it pure virtual: ServiceLevel has no apply of its own, so // it cannot be created by itself, and every concrete class must write one. // [[nodiscard]] asks the compiler to warn if a caller ignores the result. [[nodiscard]] virtual std::optional<double> apply(double price, int zone) const = 0;};
// The three cases. `final` says no class may derive from them; `override`// asks the compiler to check that each apply really replaces the base one.
class StandardService final : public ServiceLevel {public: [[nodiscard]] std::optional<double> apply(double price, int zone) const override;};
class ExpressService final : public ServiceLevel {public: [[nodiscard]] std::optional<double> apply(double price, int zone) const override;};
class OvernightService final : public ServiceLevel {public: [[nodiscard]] std::optional<double> apply(double price, int zone) const override;};
// The one object for each service; it lives as long as the program.// Returns a reference, not a copy and not an owning pointer: the caller// only uses the object, and never deletes it.const ServiceLevel& service_level(Service service);VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// The three apply functions: the three cases of the old switch, each now in// its own class. `int /*zone*/` leaves the parameter unnamed, because// standard and express do not need the zone; the comment says what it is.std::optional<double> StandardService::apply(double price, int /*zone*/) const { return price; }
std::optional<double> ExpressService::apply(double price, int /*zone*/) const { return price * 1.5;}
std::optional<double> OvernightService::apply(double price, int zone) const { if (zone == 4) return std::nullopt; // no overnight service to the islands return price * 2;}
// Turns the enum into the matching object. Each `static` local is created// once, the first time this function runs, and then lives until the program// ends, so returning a reference to it is safe: it never dangles. Since// C++11 that first creation is safe even if two threads call this at once.// Note that a switch is still needed here, to go from enum to object.const ServiceLevel& service_level(Service service) { static const StandardService standard; static const ExpressService express; static const OvernightService overnight; switch (service) { case Service::standard: return standard; case Service::express: return express; case Service::overnight: return overnight; } return standard; // not reached: every Service is handled above}
// The same rule as step 2's with_service: find the object for the// service, then make the virtual call, which runs that object's apply.std::optional<double> with_service(double price, Service service, int zone) { return service_level(service).apply(price, zone);}The three objects are function-local statics, created on first use and
destroyed when the program exits, so service_level can return a
reference that stays valid until then. Since C++11, the first use is
safe even if two threads make it at once. The golden master passed.
Then the team looked at what they had. Three classes, a base with a
virtual destructor, three statics, and a function that still has a
switch, to turn the enum into an object. And what the three classes
hold is two numbers and one flag: a factor of 1, 1.5, or 2, and
whether the service goes to the islands. A class for each case pays
off when the cases behave differently, each with its own logic. These
differ only in data.
Step 4: and back to a table
Section titled “Step 4: and back to a table”So step 4 undoes step 3, and replaces the classes with a table:
VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// Step 4 undoes step 3: the three services differ only in data, a price// factor and whether they go to the islands, so the rule is a table of// rows, one per service, and one function that reads it.namespace {
// One row of the table.struct ServiceRule { Service service; double price_factor; bool to_the_islands; // zone 4};
// The table. `constexpr` means it is fixed when the program is compiled and// can never change while it runs; `[]` lets the compiler count the rows.// Each row is written in braces, members in order: service, factor, flag.constexpr ServiceRule service_rules[] = { {Service::standard, 1.0, true}, {Service::express, 1.5, true}, {Service::overnight, 2.0, false},};
} // namespace
// The same rule as before, read from the table: find the row for the// service, refuse zone 4 if the row says the service does not go there,// otherwise multiply by the row's factor. Same prices as steps 2 and 3.std::optional<double> with_service(double price, Service service, int zone) { // Walk the rows, each one by const reference (read, not copied). for (const ServiceRule& rule : service_rules) { if (rule.service != service) continue; // not this row: try the next // The row is found; one of the next two lines always returns. if (zone == 4 && !rule.to_the_islands) return std::nullopt; return price * rule.price_factor; } // A Service with no row would end the loop and get here. All three have // rows, so this never happens, but a new service added to the enum and // not to the table would be refused here rather than priced. return std::nullopt; // not reached: every Service has a rule}The rule is now one row per service, readable at a glance, and adding a service whose behaviour is a factor and a flag is adding a row. The golden master passed again.
Text description of the diagram
Two parts, before and after. Before, step 3: with_service has a dashed “calls” arrow to service_level(Service), a switch that returns one static object for each service. A dashed “returns” arrow leads from it to the interface ServiceLevel, with a virtual apply(price, zone). Three classes have solid “is a” arrows to ServiceLevel: StandardService, ExpressService, and OvernightService, which refuses zone 4. After, step 4: with_service, which looks up the row, has a dashed “reads” arrow to the service_rules table, whose three rows are standard with factor 1.0 going to the islands, express with factor 1.5 going to the islands, and overnight with factor 2.0 not going to the islands. A flow arrow from the Before group to the After group shows the step.
Diagram source (Mermaid)
flowchart TB
subgraph Before["Before: step 3"]
B0["with_service"] -.->|calls| B1["service_level(Service)<br/>switch: one static object each"]
B1 -.->|returns| B2["ServiceLevel<br/>virtual apply(price, zone)"]
B3["StandardService"] -->|is a| B2
B4["ExpressService"] -->|is a| B2
B5["OvernightService<br/>refuses zone 4"] -->|is a| B2
end
subgraph After["After: step 4"]
A0["with_service<br/>looks up the row"] -.->|reads| A1["service_rules table<br/>standard, 1.0, islands yes<br/>express, 1.5, islands yes<br/>overnight, 2.0, islands no"]
end
Before --> AfterStep 5: the bug fix, on its own
Section titled “Step 5: the bug fix, on its own”Two things in the recording look wrong. Zones 0 and 5 do not exist and are priced at the islands’ rates, and a NaN weight is priced as one kilogram. The team checked with the people who own the price list: neither is intended, and no caller should send either. So step 5 refuses both:
VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// New in step 5: true only for the four zones that exist, 1 to 4.bool is_zone(int zone) { return zone >= 1 && zone <= 4; }
// The same as step 4's quote, with one change on the first line: a zone that// does not exist, such as 0 or 5, is now refused instead of being priced as// zone 4. Everything after that line is as before. (can_carry, on the same// line, also changed in step 5, to refuse a NaN weight.)std::optional<double> quote(const Parcel& parcel, const QuoteTerms& terms) { // Refuse the parcel if the zone is unknown OR the weight cannot be // carried; || stops at the first true part, so a bad zone is enough. if (!is_zone(parcel.zone) || !can_carry(parcel.kg)) return std::nullopt; const std::optional<double> carried = with_service(carriage(parcel.zone, parcel.kg), parcel.service, parcel.zone); if (!carried) return std::nullopt; const double handled = with_handling(*carried, parcel.fragile, terms.pickup_day); return to_charge(with_fuel_and_discount(handled, terms.fuel_surcharge_percent, terms.member));}VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// Changed in step 5: a NaN weight fails both comparisons, so it is refused.// This is the "tidier" form that changed prices when it was tried as a// refactoring in step 2. Here the change is wanted: it is a bug fix, made in// its own step and checked against its own recording. For every ordinary// number it gives the same answer as `!(kg <= 0 || kg > 30)`; only for a// NaN do they differ (this returns false, the old form true).bool can_carry(double kg) { return kg > 0 && kg <= 30; }This is a change of behaviour, and it is kept apart from the refactorings on purpose:
- The golden master fails, as it should. Run against the old recording, 1,128 lines differ.
- The difference is reviewed, line by line in kind, not by eye.
Every differing line now says -1.00, and every one is for zone 0,
zone 5, or a NaN weight: 720 for the two zones with a weight in
range, and 408 for NaN in any zone. A line outside that set would mean the change did more
than intended. Checks like these are a few lines of
grepover the diff, which is quicker and surer than reading a thousand lines. - Then the new behaviour is recorded, in its own file,
golden_quotes_v5.txt, and the test for step 5 compares with it. In real work there is one recording, and it is recorded again in the same change as the fix, so the review sees both together. - The change is announced. A caller that did send zone 0 now gets “cannot be sent” instead of a price. That belongs in the release notes, and possibly in a check of the logs first, to see whether any caller ever did.
If the fix had been made during step 2, the golden master would have failed with 1,128 differences mixed into a refactoring, and nobody could tell which were the fix and which were mistakes. Kept apart, each change has one reason, and its diff shows exactly that reason.
Tests for the rules
Section titled “Tests for the rules”Each rule now has a name and can be called on its own, so each can have unit tests with numbers worked out by hand. These are the tests the code should have had all along:
VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// The test helpers come from the site's small test header, lld_test.hpp.// LLD_TEST(name) defines one test. LLD_CHECK(condition) records a failure// if the condition is false; LLD_CHECK_EQ(actual, expected) records one if// the two differ, and prints both. A failed check does not stop the test,// so one run reports every check that failed.//// These compare prices, which are doubles, with ==. That is safe here only// because every expected value is one the code arrives at exactly: amounts// a double holds exactly, such as 12.00 and 15.00; sums written the same// way the code computes them (4.50 + 1.10); or final prices that to_charge// has rounded to the cent, which come out as the same double as the number// written directly (5.40, 25.87).
// 1 kg has no extra kilogram; 1.01 kg has one started extra kilogram;// 7.5 kg is rounded up to 8, so 7 extra kilograms at zone 3's 1.75.LLD_TEST(carriage_charges_each_started_kg_after_the_first) { LLD_CHECK_EQ(v5::carriage(1, 1.0), 4.50); LLD_CHECK_EQ(v5::carriage(1, 1.01), 4.50 + 1.10); LLD_CHECK_EQ(v5::carriage(3, 7.5), 8.25 + 7 * 1.75);}
// with_service returns an optional. `== std::nullopt` is true when it holds// nothing (refused); `== 20.00` is true when it holds that price. The second// and third checks show that only the pair overnight and zone 4 is refused.LLD_TEST(there_is_no_overnight_service_to_the_islands) { LLD_CHECK(v5::with_service(10.00, Service::overnight, 4) == std::nullopt); LLD_CHECK(v5::with_service(10.00, Service::overnight, 3) == 20.00); LLD_CHECK(v5::with_service(10.00, Service::express, 4) == 15.00);}
// Monday adds nothing; Saturday adds 2.00; a fragile parcel collected on a// Sunday gets both surcharges, 3.00 + 2.00.LLD_TEST(collection_at_the_weekend_costs_extra) { LLD_CHECK_EQ(v5::with_handling(10.00, false, Monday), 10.00); LLD_CHECK_EQ(v5::with_handling(10.00, false, Saturday), 12.00); LLD_CHECK_EQ(v5::with_handling(10.00, true, Sunday), 15.00);}
// The rule the golden master guarded with only 9 lines. 5.00 less 10% is// 4.50, under the minimum, so it is raised back to 5.00; had the minimum// come before the discount, the answer would be 4.50. 6.00 less 10% is// 5.40, over the minimum, so it stays.LLD_TEST(the_minimum_charge_applies_after_the_discount) { LLD_CHECK_EQ(v5::to_charge(v5::with_fuel_and_discount(5.00, 0, true)), 5.00); // 4.50 raised LLD_CHECK_EQ(v5::to_charge(v5::with_fuel_and_discount(6.00, 0, true)), 5.40);}
// The four ways the final version refuses a parcel: a zone that does not// exist (5), too heavy (30.01 kg), a NaN weight (std::nan("") makes one),// and overnight to the islands. The first and third were priced before the// fix in step 5.LLD_TEST(a_parcel_that_cannot_be_sent_has_no_price) { // Monday, no fuel surcharge, not a member: terms that add nothing. const QuoteTerms terms{Monday, 0, false}; LLD_CHECK(v5::quote(Parcel{5, 1.0, Service::standard, false}, terms) == std::nullopt); LLD_CHECK(v5::quote(Parcel{1, 30.01, Service::standard, false}, terms) == std::nullopt); LLD_CHECK(v5::quote(Parcel{1, std::nan(""), Service::standard, false}, terms) == std::nullopt); LLD_CHECK(v5::quote(Parcel{4, 1.0, Service::overnight, false}, terms) == std::nullopt);}
// One parcel through every rule, each step worked out by hand below. It is// the same parcel as line 1486 of the recording.LLD_TEST(every_rule_together_worked_by_hand) { // 6.00 + 7 x 1.10 = 13.70; express x 1.5 = 20.55; fragile + 3 = 23.55; // Saturday + 2 = 25.55; fuel x 1.125 = 28.74375; member x 0.9 = // 25.869375; rounded to the cent, 25.87. const Parcel parcel{2, 7.5, Service::express, true}; const QuoteTerms terms{Saturday, 12.5, true}; LLD_CHECK(v5::quote(parcel, terms) == 25.87);}They are fewer than 3,456 lines and say much more: each names a rule, and a failure says which rule broke. The minimum charge, which the golden master guarded with 9 lines, has a test of its own. Once tests like these cover every rule, and the last caller has moved to the new interface, the golden master has done its job and can be deleted, with its 200 KB recording.
The demo quotes three parcels through the new interface:
2.5 kg to zone 1, standard, Tuesday: $7.547.5 kg to zone 2, express, fragile, member, Saturday: $25.871 kg to zone 4, overnight, Tuesday: cannot be sentThe whole sequence, from the function as it was found to the fix:
Text description of the diagram
A flowchart. The legacy quote, which reads the clock and a global, leads by an arrow labelled “step 1, checked by reading” to step 1, the seam, where the day and the fuel surcharge are parameters. From step 1 an arrow labelled “record” leads to the recording golden_quotes.txt, of 3,456 lines. Step 1 leads to step 2, parameter objects, an enum, an optional, and named rules; step 2 leads to step 3, a class per service; step 3 leads to step 4, a table of services. Dashed arrows labelled “must match exactly” lead from the recording to steps 2, 3, and 4. Step 4 leads by an arrow labelled “behaviour change” to step 5, which refuses zones 0 and 5 and NaN weights. From step 5 an arrow labelled “review the diff, then record” leads to the recording golden_quotes_v5.txt, and another arrow leads to unit tests for each rule.
Diagram source (Mermaid)
flowchart TB
L["Legacy quote<br/>reads the clock and a global"] -->|"step 1, checked by reading"| S1["Step 1: seam<br/>day and fuel are parameters"]
S1 -->|record| G1[("golden_quotes.txt<br/>3,456 lines")]
S1 --> S2["Step 2: parameter objects,<br/>enum, optional, named rules"]
S2 --> S3["Step 3: a class per service"]
S3 --> S4["Step 4: a table of services"]
G1 -.->|"must match exactly"| S2
G1 -.->|"must match exactly"| S3
G1 -.->|"must match exactly"| S4
S4 -->|"behaviour change"| S5["Step 5: refuse zones 0 and 5<br/>and NaN weights"]
S5 -->|"review the diff, then record"| G5[("golden_quotes_v5.txt")]
S5 --> U["Unit tests for each rule"]When a golden master fits, and when it does not
Section titled “When a golden master fits, and when it does not”It fits code whose results can be printed, and whose inputs can be listed: price and tax rules, parsers, formatters, report generators, and functions that turn one data structure into another. It fits best when the code is too tangled to work out by hand, and when it is about to change shape, not behaviour.
It needs more work, or something else, when:
- The output is not the same on every run. Timestamps, generated ids, and the order of a hash map’s entries change every time. They have to be fixed by a seam, or scrubbed from the lines, before the recording can be compared.
- The inputs cannot be listed. For a function of a few numbers, a grid of edges works. For a function of a whole document or a long sequence of events, the recording needs a set of real or generated inputs, chosen with a fixed seed as in property-based and table-driven tests, and its strength has to be checked the same way as here.
- The code has undefined behaviour. A recording of a read past the end of an array records an accident; another compiler, or the next build, may give another accident. Such inputs are left out of the grid and fixed in a step of their own.
- The point of the change is behaviour. A golden master says “nothing changed”. For a change that is meant to change things, it can only check that nothing else did, as in step 5.
Common mistakes
Section titled “Common mistakes”- Fixing things during the first, untested step. Step 1 is safe only because it is small enough to check by reading. Every rename or fix added to it makes the reading harder, with nothing else to check it.
- Recording without reading. A recording made from a broken build, or with a bug in the test that prints the lines, pins the wrong thing for every step after it.
- Choosing grid values that cannot tell rules apart. 7.5 kg rounds and ceils to the same number, so it cannot tell the two apart. Ask, for each value, what mistake it would catch; then check with a few deliberate mistakes.
- Leaving out the inputs nobody should send. Zones that do not exist and NaN weights are exactly where a “tidier” rewrite of a condition changes behaviour.
- Recording again to make a failing test pass. The point of the failure is the diff. A new recording is made only for a change of behaviour someone decided on, after the diff has been reviewed.
- Mixing a bug fix into a refactoring. The test then fails for two reasons at once, and the diff cannot say which line belongs to which.
- Keeping the golden master for ever. It pins everything, including what nobody cares about, so every later change of behaviour has to record it again. Once each rule has its own tests, it has done its job.
When the requirements change
Section titled “When the requirements change”The new service arrives: “same day, for zones 1 and 2 only, at three
times the standard price, if ordered before 11:00”. The factor and
the zones fit the table, with a column for which zones the service
reaches instead of a flag for the islands. The cut-off time does not:
it is a rule about when the order is placed, which the function cannot
see. That needs a new input, the time of the order, in QuoteTerms,
and a new rule. Adding it is a change of behaviour, made with the new
rule’s own unit tests, and the golden master, if it is still kept,
shows that every existing service’s prices are unchanged. Evolving a
design through a series of such changes is the subject of the next
page in this section, on incremental design evolution.
Exercise
Section titled “Exercise”Exercise: Plan the refactoring steps
A tool-hire shop charges a fee when a tool comes back late. This function, compiled with both compilers, has worked for years, and is about to be refactored before new rules for weekly hire arrive:
#include <cstring>#include <ctime>
// The shop's settings, one global object for the whole program.struct Config { bool cap_fees = true;};Config g_config; // loaded at startup
// The late fee for a returned item, in cents.// item_type: the kind of tool, as C text (a pointer to characters ending in// a zero byte), such as "drill". due: when it was due back, as a// std::time_t, a count of seconds.int late_fee_cents(const char* item_type, std::time_t due) { // std::time(nullptr) is the current time, from the system clock. The // difference is in seconds, and 86400 is the number of seconds in a // day. On the usual platforms std::time_t is a whole number, so the // division drops any part of a day. const int days_late = static_cast<int>((std::time(nullptr) - due) / 86400); if (days_late <= 0) return 0; // on time or early: no fee int per_day; // std::strcmp compares two C strings and returns 0 when they are equal, // character for character, upper and lower case included. if (std::strcmp(item_type, "drill") == 0) { per_day = 25; } else if (std::strcmp(item_type, "saw") == 0) { per_day = 100; } else { per_day = 50; } int fee = days_late * per_day; // If the setting is on, no fee is more than 1500 cents. if (g_config.cap_fees && fee > 1500) fee = 1500; return fee;}- What are its hidden inputs? Write the first step, the one made without a net.
- Choose the grid for a golden master. Which values of each input, and why each?
- Which input should not be in the grid at all, and why?
- List the refactoring steps you would take after that, in order, naming each.
- While reading, you notice that an item 23 hours and 59 minutes late pays nothing, and that “Drill” with a capital D pays the default rate. Which, if either, do you fix during the refactoring?
Show the explained answer
-
The clock and the setting.
std::time(nullptr)andg_config.cap_feesare read inside the body. Make both parameters, change nothing else, and keep the old signature, which passes the real time and the global. This was compiled with both compilers:// Step 1: the clock and the setting become parameters; nothing else changes.int late_fee_cents(const char* item_type, std::time_t due, std::time_t now, bool cap_fees) {// `now`, the argument, replaces std::time(nullptr); nothing else// on this line changes.const int days_late = static_cast<int>((now - due) / 86400);if (days_late <= 0) return 0;int per_day;if (std::strcmp(item_type, "drill") == 0) {per_day = 25;} else if (std::strcmp(item_type, "saw") == 0) {per_day = 100;} else {per_day = 50;}int fee = days_late * per_day;if (cap_fees && fee > 1500) fee = 1500; // the argument, not g_configreturn fee;}// The old signature, for every caller.// It reads the clock and the global, exactly as the old body did, and// passes them on, so every existing call gets the same fee as before.int late_fee_cents(const char* item_type, std::time_t due) {return late_fee_cents(item_type, due, std::time(nullptr), g_config.cap_fees);}A reviewer checks it by a diff: inside the body, only the two lines that read the clock and the setting differ.
-
A grid of edges, with
nowfixed. Pass a fixednowand setduetonowminus an offset:- Item types: “drill”, “saw”, and something else, such as “ladder”, which gets the default rate. Add “Drill” and “” too, since the comparison is exact and the recording should show what they get.
- Lateness, in seconds: a day early (-86,400), exactly on time
(0), one second short of a day (86,399), exactly a day (86,400),
and just over (86,401), for the division and the
<= 0check; then 59 and 61 days, either side of 60, where a drill reaches the 1,500 cap. A saw reaches it at 15 days and the default rate at 30, so add 15 and 16 days, and 30 and 31. At exactly 1,500,>and>=give the same fee, so no input tells those two apart. - The cap: on and off.
A scratch grid of the first three types, the first seven offsets, and both settings, 42 lines, was run with both compilers and gave the same lines; for example, a saw 86,399 seconds late pays 0, at 86,400 seconds it pays 100, and at 59 days it pays 5,900 without the cap and 1,500 with it.
-
A null
item_type.std::strcmpon a null pointer is undefined behaviour, so there is no behaviour to record: the recording might say anything, or the test might crash. Leave it out of the grid, note it, and decide in a behaviour change what a null type should do, or make it impossible by taking astd::string_viewat the new interface. -
One possible order:
- Replace the type code with an enum,
ItemType, with a function that turns the old strings into it, keeping “anything else” as its own value,other, with the default rate. - Introduce a parameter object for the hire: the type and the due time.
- Extract function for each rule:
days_late(due, now),rate_per_day(type), andcapped(fee, cap_fees). - Replace the chain of
ifs on the type with a table of rates, since the types differ only in a number. - Run the golden master after each one.
A class per item type is the wrong shape for now, for the same reason as in step 3 above: the types differ only in data. The weekly hire rules may change that, and that is a decision for the change that adds them.
- Replace the type code with an enum,
-
Neither, during the refactoring. Both are what the code does today, and a caller, or a reader of past fee notices, may expect them. Pin both in the recording, finish the refactoring, then ask the people who own the rules. If either is a bug, fix it in its own step, review the diff of the recording, which should show only the lines for those inputs, record again, and announce the change.
Summary
Section titled “Summary”- The first change to untested legacy code is made without a net, so it must be small enough to check by reading: make the hidden inputs parameters, keep the old signature, change nothing else.
- A golden master records what the code does over a grid of inputs, one line per input, and checks every later step against the recording. It is cheap to build and catches differences nobody would see by reading.
- The grid decides what the net catches. Choose values on both sides of every edge, include the odd inputs the code accepts, and test the grid with a few deliberate mistakes.
- Refactorings are small, named by what they do, and taken one at a time: introduce parameter object, extract function, replace a type code with an enum, replace conditional with polymorphism, and, when the cases differ only in data, back to a table.
- “Obviously the same” changes can change results: writing
kg > 0for!(kg <= 0)changes what happens to NaN, and reordering multiplications ofdoublevalues can move a price by a cent. - A bug fix is a separate step. The recording’s diff is reviewed in kind, the new behaviour is recorded deliberately, and the change is announced.
- Once each rule has its own unit tests, the golden master has done its job and can be deleted.