Skip to content

Refactoring toward principles

Difficulty: Intermediate

Key concepts

  • refactoring
  • characterization test
  • small steps
  • refactoring versus adding a feature
  • balancing principles
  • stopping point
  • What refactoring is, and why it is a different activity from adding a feature.
  • How to pin what code does today with a characterization test before you touch it.
  • How to choose the next small step from a change you actually need, not from a list of principles.
  • How the principles from this section show up as concrete steps: single responsibility, don’t repeat yourself, and separation of concerns.
  • How to recognise when two principles pull in different directions, and how to decide; here, the open/closed principle loses to keeping it simple.
  • When to stop.

A tool-hire shop prints a statement when a customer brings their tools back. The code that prints it was written quickly when the shop opened and has worked since.

Requirements the code meets today:

  1. FR-1 A statement lists each hire as the tool’s name, its category, the number of days, and the hire charge, then the hire total, the refundable deposits, and the amount due.
  2. FR-2 A tool is hired by the day. A full week costs five days: 9 days are charged as 7 days (one week at 5, plus 2).
  3. FR-3 Heavy equipment is charged for at least two days.
  4. FR-4 Power tools carry a 50.00 refundable deposit per hire.
  5. FR-5 A hire shorter than one day is an error and is refused.

Two new requests arrive in the same week:

  1. FR-6 Counter staff want to give a quote before a hire starts: drill (power), 7 days: 75.00 plus 50.00 refundable deposit.
  2. FR-7 The accounts team wants each statement’s totals as numbers, to add up at the end of the month, instead of copying them from printed text.

Here is the code. It is one function:

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

hire.hpp
// The three kinds of tool. The kind decides the extra rules: power tools
// take a deposit, heavy equipment has a two-day minimum. `enum class`
// keeps the names inside the type: Category::power, not just power.
enum class Category { hand, power, heavy };
// A tool the shop hires out. Money is a whole number of cents in a
// `long long` (1500 is 15.00), so there is no floating-point rounding.
struct Tool {
std::string name;
Category category;
long long daily_rate_cents;
};
// One hire: which tool, for how many days. The Tool is held by value, a
// copy, so a Hire does not depend on any other object staying alive.
struct Hire {
Tool tool;
int days; // at least 1
};
// A customer and everything they hired, in order.
struct Customer {
std::string name;
std::vector<Hire> hires;
};

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

v1.cpp
// The starting point: one function that does everything. For each hire it
// checks the days, works out the label, the deposit, and the price, and
// writes a line of text; then it writes the three totals. It returns the
// whole statement as one string. Throws std::invalid_argument for a hire
// shorter than one day (FR-5). Correct, but every rule is buried in here.
std::string statement(const Customer& customer) {
std::string text = "Hire statement for " + customer.name + "\n";
long long total = 0; // the hire charges added so far, in cents
long long deposits = 0; // the deposits added so far, in cents
for (const Hire& hire : customer.hires) {
if (hire.days < 1) {
throw std::invalid_argument{hire.tool.name + ": a hire lasts at least 1 day"};
}
// `days` starts as the days hired and becomes the days CHARGED;
// hire.days itself is kept, because the printed line shows it.
int days = hire.days;
std::string kind; // the category's label, for the printed line
// One switch doing three different jobs: the label (every case),
// the deposit (power), and the two-day minimum (heavy).
switch (hire.tool.category) {
case Category::hand:
kind = "hand";
break;
case Category::power:
kind = "power";
deposits += 5000; // refundable deposit
break;
case Category::heavy:
kind = "heavy";
days = std::max(days, 2); // two-day minimum
break;
}
// The week rule. Integer division drops the remainder, so days / 7
// is the number of whole weeks, each charged as 5 days, and
// days % 7 (the remainder) is the extra days, charged as they are.
// 9 days: 9 / 7 = 1 week -> 5, plus 9 % 7 = 2, so 7 days charged.
days = days / 7 * 5 + days % 7; // a full week costs five days
// `days` (an int) is converted to long long before the multiply.
const long long amount = days * hire.tool.daily_rate_cents;
total += amount;
// Turn cents into "units.cents" text. snprintf writes into the
// char buffer `money`, never more than sizeof money (32) bytes.
// "%lld" prints amount / 100 (the whole units); "%02lld" prints
// amount % 100 (the cents) with at least 2 digits, padded with 0:
// 4500 -> "45.00", 1205 -> "12.05". This format is written again,
// three more times, below.
char money[32];
std::snprintf(money, sizeof money, "%lld.%02lld", amount / 100, amount % 100);
// The line shows the days HIRED (hire.days), not the days charged,
// and `?:` picks "day" for exactly 1 and "days" otherwise.
text += " " + hire.tool.name + " (" + kind + "), " + std::to_string(hire.days) +
(hire.days == 1 ? " day: " : " days: ") + money + "\n";
}
// A second buffer, also named `money`: the first one belonged to the
// loop body and no longer exists here. It is reused for all three
// totals.
char money[32];
std::snprintf(money, sizeof money, "%lld.%02lld", total / 100, total % 100);
text += "Hire total: " + std::string{money} + "\n";
std::snprintf(money, sizeof money, "%lld.%02lld", deposits / 100, deposits % 100);
text += "Deposits (refundable): " + std::string{money} + "\n";
std::snprintf(money, sizeof money, "%lld.%02lld", (total + deposits) / 100,
(total + deposits) % 100);
text += "Amount due: " + std::string{money} + "\n";
return text;
}
How this code works: v1::statement

The function builds one long string, text, and keeps two running totals in cents, total and deposits. Then, for each hire, in order:

  1. Refuse a bad hire. Fewer than one day throws std::invalid_argument, and no statement is returned at all.
  2. Copy the days. days starts as the days hired. The rules below change days into the days charged; hire.days stays as it was, because the printed line shows the days hired.
  3. The switch on the category does three unrelated jobs at once: it sets the label kind for every category, adds the 50.00 deposit for a power tool, and raises a heavy hire to at least two days with std::max(days, 2).
  4. The week rule. days / 7 * 5 + days % 7: with whole numbers, days / 7 is the number of full weeks (the remainder is dropped), each charged as 5 days, and days % 7 is the days left over.
  5. The price is the days charged times the daily rate, added to total.
  6. The line of text. snprintf turns the cents into text such as 45.00, and the line is appended to text.

After the loop, the same snprintf format is used three more times for the hire total, the deposits, and the amount due (their sum).

A worked example: Kim, the customer used in the tests and in main.

Hire Category days after the switch Days charged amount (cents) total deposits
drill, 3 days power 3 0 × 5 + 3 = 3 3 × 1500 = 4500 4500 5000
ladder, 9 days hand 9 1 × 5 + 2 = 7 7 × 800 = 5600 10100 5000
digger, 1 day heavy 2 (the minimum) 0 × 5 + 2 = 2 2 × 12000 = 24000 34100 5000

The three totals are then 341.00, 50.00, and 391.00, the last three lines of the pinned statement below. Notice how each rule (the deposit, the minimum, the week rule, the money format) is reachable only by running the whole loop: that is what the next steps change.

The code is not wrong. Every rule is there and the output is correct. It is hard to change, and two changes have just been asked for:

  • The quote (FR-6) needs the pricing rules, but they are written inside the statement loop, mixed with the category label. The only way to reuse them is to copy them, and then the week rule lives in two places.
  • The totals (FR-7) are local variables that exist only while the text is being built. There is no way to get them as numbers.
  • The money format is written four times. A change to how money is shown (a currency symbol, say) is four edits.
  • No pricing rule can be tested on its own. To check the week rule you must build a whole statement and search the text for one number.

Refactoring changes the structure of code without changing what it does. Adding a feature changes what it does. Do them as separate steps and never in the same step, because each kind of step has a different way of being checked:

Kind of step What should change How you know it worked
Refactoring The structure, not the behaviour The existing tests pass, unchanged
Adding a feature The behaviour New tests pass, and the old ones still pass

If you restructure and add a feature at the same time and a test fails, you cannot tell which one broke it. If you keep them apart, a failing test after a refactoring step means “undo that step”, and you lose a few minutes, not a day.

The plan for this page is therefore: refactor until the two new requests are easy, then add them as ordinary small changes.

A characterization test describes what the code does, not what the requirements say it should do. You write it by running the current code, copying its output into the test, and then checking that output by hand against the rules you know. If the code has a bug, the test pins the bug too, and that is deliberate: a refactoring must not change behaviour, not even wrong behaviour. A bug is fixed in its own step, with its own test change, so that the fix is a decision and not an accident.

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

test_statement.cpp
// Step 1: pin today's behaviour before changing anything. The expected
// text was copied from what the first version printed, then checked by
// hand against the pricing rules.
// Adjacent string literals ("a" "b") are joined into one by the compiler,
// so this is one std::string, one line of the statement per literal.
// kim() and the three Tools are helpers just above this snippet: Kim
// hires a drill (power, 15.00 a day) for 3 days, a ladder (hand, 8.00)
// for 9, and a mini digger (heavy, 120.00) for 1.
const std::string expected_statement =
"Hire statement for Kim\n"
" drill (power), 3 days: 45.00\n"
" ladder (hand), 9 days: 56.00\n"
" mini digger (heavy), 1 day: 240.00\n"
"Hire total: 341.00\n"
"Deposits (refundable): 50.00\n"
"Amount due: 391.00\n";
// LLD_TEST(name) defines one test. LLD_CHECK_EQ(actual, expected) fails,
// and prints both values, unless they are equal; LLD_CHECK_THROWS(
// expression, type) fails unless the expression throws that type of
// exception. They come from the site's small test header, lld_test.hpp.
// This test proves each version prints exactly the pinned text.
LLD_TEST(every_version_prints_the_pinned_statement) {
LLD_CHECK_EQ(v1::statement(kim()), expected_statement);
LLD_CHECK_EQ(v2::statement(kim()), expected_statement);
LLD_CHECK_EQ(v3::statement(kim()), expected_statement);
}
// FR-5, pinned too: a hire of 0 days is refused by every version.
LLD_TEST(every_version_refuses_a_zero_day_hire) {
const Customer bad{"Lee", {{drill, 0}}};
LLD_CHECK_THROWS(v1::statement(bad), std::invalid_argument);
LLD_CHECK_THROWS(v2::statement(bad), std::invalid_argument);
LLD_CHECK_THROWS(v3::statement(bad), std::invalid_argument);
}

Choose the input to reach every rule at least once. A single customer with three hires is enough here, because each hire exercises different rules:

Hire Rules it reaches Charge worked by hand
drill, 3 days power deposit (FR-4) 3 × 15.00 = 45.00, deposit 50.00
ladder, 9 days week rule (FR-2), plural “days” (5 + 2) × 8.00 = 56.00
digger, 1 day heavy minimum (FR-3), singular “day” 2 × 120.00 = 240.00

The second test pins FR-5: a zero-day hire is refused. Both tests call all three versions of statement in this example, because each version is kept so that you can compare them. In your own code there is one version, edited in place, and the test calls it.

What the pin does not cover. One customer cannot reach every case: a heavy hire that also crosses a week, a customer with no hires, a very large amount. Add inputs when a step touches code they would reach. A characterization test is a safety net with a known size, not a proof. For code too tangled to work out by hand, the page on refactoring safely in small steps records a golden master over thousands of inputs instead, and shows how to measure the size of that net.

Step 2: give each rule a name and one home

Section titled “Step 2: give each rule a name and one home”

The first pain is that the quote needs the pricing rules and the statement owns them. The smallest step that helps is to extract each rule into a function, so the statement and the quote can both call it.

Which principles does this serve?

  • Single responsibility. The pricing rules change when the shop changes its prices. The statement layout changes when the shop changes its paperwork. Those are different reasons, decided by different people, so they should live in different functions.
  • Don’t repeat yourself. The money format was written four times. It is one piece of knowledge (“amounts are shown as units, a dot, and two digits”), so it gets one home: money.

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

v2.hpp
// The charge for one hire, in cents, with every pricing rule applied
// (heavy minimum, then the week rule). Throws std::invalid_argument if the
// hire is shorter than one day.
long long hire_cents(const Hire& hire);
// The refundable deposit for one hire: 5000 cents for a power tool, else 0.
long long deposit_cents(const Hire& hire);
// The one home of the money format.
std::string money(long long cents); // 1234 -> "12.34"
// "hand", "power", or "heavy". std::string_view: a read-only view of text
// that already exists (here, string literals), so nothing is copied.
std::string_view category_name(Category category);
// The same output as v1::statement, built from the functions above.
std::string statement(const Customer& customer);

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

v2.cpp
long long hire_cents(const Hire& hire) {
if (hire.days < 1) {
throw std::invalid_argument{hire.tool.name + ": a hire lasts at least 1 day"};
}
// Heavy equipment is charged for at least two days. `?:` chooses:
// for heavy, std::max(hire.days, 2) (so 1 day becomes 2); for anything
// else, the days as hired.
int days = hire.tool.category == Category::heavy ? std::max(hire.days, 2) : hire.days;
// Whole weeks (days / 7, integer division) cost 5 days each; the days
// left over (days % 7) cost one each. 7 -> 5, 9 -> 7, 15 -> 11.
days = days / 7 * 5 + days % 7; // a full week costs five days
return days * hire.tool.daily_rate_cents;
}
long long deposit_cents(const Hire& hire) {
return hire.tool.category == Category::power ? 5000 : 0; // refundable
}
// Written once instead of four times. snprintf fills the buffer: the whole
// units (cents / 100), a dot, then the cents (cents % 100) as at least two
// digits padded with 0, so 4500 -> "45.00" and 1205 -> "12.05". Returning
// the char array builds a std::string copy of it, so the buffer can safely
// disappear when the function ends. Meant for amounts of 0 or more.
std::string money(long long cents) {
char text[32];
std::snprintf(text, sizeof text, "%lld.%02lld", cents / 100, cents % 100);
return text;
}

The statement now reads as a description of the statement, not of the pricing:

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

v2.cpp
// The same loop as v1, but each rule is now a call with a name. The
// output is byte for byte the same, which is what the pinned test checks.
// hire_cents still throws for a hire shorter than one day.
std::string statement(const Customer& customer) {
std::string text = "Hire statement for " + customer.name + "\n";
long long total = 0;
long long deposits = 0;
for (const Hire& hire : customer.hires) {
const long long amount = hire_cents(hire);
total += amount;
deposits += deposit_cents(hire);
// std::string{...} turns the string_view into a std::string, so it
// can be joined with + to the text around it.
text += " " + hire.tool.name + " (" + std::string{category_name(hire.tool.category)} +
"), " + std::to_string(hire.days) + (hire.days == 1 ? " day: " : " days: ") +
money(amount) + "\n";
}
text += "Hire total: " + money(total) + "\n";
text += "Deposits (refundable): " + money(deposits) + "\n";
text += "Amount due: " + money(total + deposits) + "\n";
return text;
}

Run the pin. It passes, unchanged. That is the whole point: the code is structured differently and does exactly the same thing.

One switch became three pieces. In the first version, one switch set the label, added the deposit, and applied the heavy minimum. It looked like one piece of knowledge because it was one block of code, but it was three: a label, a deposit policy, and a pricing rule. The label went to category_name, the deposit to deposit_cents, and the minimum joined the week rule in hire_cents, because both decide how many days are charged. They change for different reasons, so splitting them is not repetition. Two pieces of code that look alike but change for different reasons are not a DRY problem; one piece of code that does three jobs is an SRP problem.

Know what the pin does not check. hire_cents refuses a hire shorter than one day with the same message the old loop used, including the tool’s name. The second pinned test checks only the exception type, not the message, so if a step dropped the tool’s name from the message, no test would notice. If counter staff rely on that message, it is behaviour, and the pin should check it too.

Step 2: the rules move out of the statement loop into named functions the statement calls
Text description of the diagram

Two parts, before and after. Before: a single box, statement(customer), whose loop switches on the category and holds the label, the deposit, the heavy minimum, the week rule, and four copies of the money format. After: statement(customer) holds only the loop and the layout, and has dashed arrows labelled “calls” to four functions: hire_cents(hire), which holds the heavy minimum and the week rule; deposit_cents(hire); money(cents); and category_name(category). A flow arrow from the Before group to the After group shows the step.

Diagram source (Mermaid)
flowchart TB
subgraph Before
  B1["statement(customer)<br/>loop: switch on category<br/>label, deposit, heavy minimum<br/>week rule, 4 copies of the money format"]
end
subgraph After
  A1["statement(customer)<br/>loop and layout"] -.->|calls| A2["hire_cents(hire)<br/>heavy minimum, week rule"]
  A1 -.->|calls| A3["deposit_cents(hire)"]
  A1 -.->|calls| A4["money(cents)"]
  A1 -.->|calls| A5["category_name(category)"]
end
Before --> After

Step 3: separate working out the statement from writing it

Section titled “Step 3: separate working out the statement from writing it”

The second pain is FR-7: the totals exist only as text. The statement function still does two jobs, and they are now easy to see: it works out the lines and totals, and it writes them as text. This is separation of concerns: computing a result and presenting it are different concerns, and mixing them means every new use of the numbers has to parse text.

The step introduces one value type, Statement, between the two jobs:

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

v3.hpp
// Throws std::invalid_argument if the hire is shorter than one day.
long long hire_cents(const Hire& hire);
long long deposit_cents(const Hire& hire);
std::string money(long long cents); // 1234 -> "12.34"
std::string_view category_name(Category category);
// One line of a statement, already worked out: the words describing the
// hire and its charge in cents.
struct StatementLine {
std::string description; // "drill (power), 3 days"
long long amount_cents;
};
// The whole statement as numbers, before any text is written. A plain
// struct with public members: it is a result to read, with no rule the
// code must protect after it is built.
struct Statement {
std::string customer; // the customer's name
std::vector<StatementLine> lines; // one per hire, in order
long long hire_total_cents; // sum of the lines' amounts
long long deposit_total_cents; // sum of the deposits
};
// Works out every line and total. Throws std::invalid_argument for a
// hire shorter than one day. Returns the Statement by value.
Statement build_statement(const Customer& customer); // the numbers
// Writes a Statement as the text the shop prints. Only reads the
// Statement. It has no checks of its own, so it never refuses a Statement
// (building the strings can still fail if memory runs out).
std::string format_text(const Statement& statement); // the words
// format_text(build_statement(customer)): same name, same output as v1.
std::string statement(const Customer& customer); // both, as before

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

v3.cpp
// The first job: the numbers. No text formatting of money happens here.
Statement build_statement(const Customer& customer) {
// Fields in the order Statement declares them: a copy of the name, no
// lines yet ({} is an empty vector), and both totals at 0.
Statement result{customer.name, {}, 0, 0};
for (const Hire& hire : customer.hires) {
// Throws for a bad hire, so no Statement is returned at all.
const long long amount = hire_cents(hire);
// {describe(hire), amount} builds a temporary StatementLine, which
// push_back moves into the vector. describe is a private helper
// in this file that gives text such as "drill (power), 3 days".
result.lines.push_back({describe(hire), amount});
result.hire_total_cents += amount;
result.deposit_total_cents += deposit_cents(hire);
}
return result;
}
// The second job: the words. Only reads the Statement, and uses money()
// for every amount, so the format still lives in one place.
std::string format_text(const Statement& statement) {
std::string text = "Hire statement for " + statement.customer + "\n";
for (const StatementLine& line : statement.lines) {
text += " " + line.description + ": " + money(line.amount_cents) + "\n";
}
text += "Hire total: " + money(statement.hire_total_cents) + "\n";
text += "Deposits (refundable): " + money(statement.deposit_total_cents) + "\n";
text += "Amount due: " +
money(statement.hire_total_cents + statement.deposit_total_cents) + "\n";
return text;
}
// The old name and output, kept for every existing caller. The Statement
// returned by build_statement is a temporary: it lives until format_text
// has finished with it, then it is destroyed.
std::string statement(const Customer& customer) {
return format_text(build_statement(customer));
}

statement(customer) keeps its name and its exact output, so every caller and the pin keep working. It is now one line: format_text(build_statement(customer)). The accounts team (FR-7) can call build_statement and read hire_total_cents directly.

Why a struct and not a class? Statement is a result: a set of values with no rule that ties them together that the code must protect after it is built. Plain public members are the honest design. If the totals had to stay equal to the sum of the lines while callers edited the lines, that would be an invariant, and then a class with private members would be right.

Step 3: one function that computes and writes becomes two, joined by a Statement value
Text description of the diagram

Two parts, before and after. Before: statement(customer), which both computes and writes text, has a flow arrow to a std::string. After: build_statement(customer), which computes the numbers, has a flow arrow to a Statement value holding the lines, the hire total, and the deposit total. The Statement has two flow arrows: one to format_text(statement), which writes the words and leads to a std::string, and one to the month-end totals for FR-7. A flow arrow from the Before group to the After group shows the step.

Diagram source (Mermaid)
flowchart LR
subgraph Before
  B1["statement(customer)<br/>computes and writes text"] --> B2["std::string"]
end
subgraph After
  A1["build_statement(customer)<br/>the numbers"] --> A2["Statement<br/>lines, hire total, deposit total"]
  A2 --> A3["format_text(statement)<br/>the words"]
  A3 --> A4["std::string"]
  A2 --> A5["month-end totals<br/>FR-7"]
end
Before --> After

After this step, the numbers can be tested as numbers:

// The numbers, with no text at all: 4500 + 5600 + 24000 = 34100 cents.
const v3::Statement statement = v3::build_statement(kim());
LLD_CHECK_EQ(statement.hire_total_cents, 34100);

That test is shorter, and when it fails it names the one number that is wrong. A failing pin shows two whole statements, and you must find the difference yourself.

The refactoring is done; now the feature. This step changes behaviour, so it comes with new tests, and the pin must still pass because the statement must not change.

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

v3.hpp
// What a hire would cost, before it starts. Uses the same rules as the
// statement because it calls the same functions. Returns one line of
// text, e.g. "drill (power), 7 days: 75.00 plus 50.00 refundable deposit".
// Throws std::invalid_argument for fewer than one day.
std::string quote(const Tool& tool, int days);

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

v3.cpp
std::string quote(const Tool& tool, int days) {
// Build the hire that would happen (a copy of the tool), and ask the
// same functions a statement asks.
const Hire hire{tool, days};
// hire_cents throws here for days < 1, before anything is returned.
std::string text = describe(hire) + ": " + money(hire_cents(hire));
// An if with an initializer: `deposit` is created, then tested, and
// exists only inside this if. The deposit is mentioned only when there
// is one.
if (const long long deposit = deposit_cents(hire); deposit > 0) {
text += " plus " + money(deposit) + " refundable deposit";
}
return text;
}

The body of quote is six lines because the work it needs already has names: hire_cents, deposit_cents, money, and the private helper describe that build_statement also uses. A quote and a statement cannot disagree about a price, because they run the same code. Before step 2, adding a quote would have meant copying the switch and the week rule, and the first price change would have updated one copy.

The switch on Category and the comparisons against Category::heavy and Category::power are a textbook trigger for “replace the conditional with polymorphism”: a Tool base class with a virtual hire_cents, and HandTool, PowerTool, and HeavyTool overriding it. The open/closed principle seems to ask for it: a new category would be a new class, and no existing function would change.

This page does not take that step. The reasons are specific to this code, which is how such a decision should be made:

  • No change is asking for it. Neither FR-6 nor FR-7 adds a category. The shop has had three categories since it opened.
  • The rules are tiny. Each category differs by one line: a deposit or a minimum. Three classes with one overridden function each would spread three lines across three files.
  • A category is data. Tool is a value: it is copied into each Hire, could be compared, and could be loaded from a price list. A class hierarchy would make it a pointer to a heap object with an owner, so Hire would need std::unique_ptr<Tool> and could no longer be copied by default.
  • The compiler already helps. category_name switches over the enumeration with no default:, so with -Wall GCC and Clang warn if a new category is added and not handled there. The examples on this site also build with -Werror, which turns that warning into an error.

That last point has a gap that is worth knowing: the comparisons in hire_cents and deposit_cents are not switch statements, so a new category gets no warning there. It silently pays no deposit and has no minimum. If categories start arriving often, that gap is the first real reason to revisit this decision, and the cheaper fix is to turn those two comparisons into switch statements with no default:, not to build a hierarchy.

struct Hire

hire.hpp, unchanged by every step

Data members

  • Tool tool;
  • int days; at least 1

struct StatementLine

Data members

  • std::string description; "drill (power), 3 days"
  • long long amount_cents;

struct Statement

Data members

  • std::string customer;
  • std::vector<StatementLine> lines;
  • long long hire_total_cents;
  • long long deposit_total_cents;

namespace v3

Functions

  • long long hire_cents(const Hire& hire); throws std::invalid_argument
  • long long deposit_cents(const Hire& hire);
  • std::string money(long long cents);
  • std::string_view category_name(Category category);
  • Statement build_statement(const Customer& customer); the numbers
  • std::string format_text(const Statement& statement); the words
  • std::string statement(const Customer& customer); both, as before
  • std::string quote(const Tool& tool, int days); FR-6
After step 4: the shared data, a result value, and free functions in one namespace

Tool, Customer, and the Category enumeration are in hire.hpp too and are left out of the outline; no step changed them. In the example, StatementLine and Statement are inside namespace v3. The helper describe is in an unnamed namespace in v3.cpp, so it is not part of the header at all.

Why free functions and not a StatementPrinter class? None of these functions has state to keep between calls. A class would add an object to create and a name that adds nothing, which is the “class with one function” problem from the cost of unnecessary abstraction. If the prices came from a price list loaded at start-up, that list would be state, and a PriceList class holding it would be the natural next step.

After step 4: the statement and the quote reach the same pricing functions
Text description of the diagram

statement(customer) has dashed “calls” arrows to build_statement and format_text. build_statement calls hire_cents, deposit_cents, and describe, which is private to v3.cpp. format_text calls money. quote(tool, days), for FR-6, calls hire_cents, deposit_cents, describe, and money. describe calls category_name. The statement and the quote share every pricing function; neither has its own copy of a rule.

Diagram source (Mermaid)
flowchart TB
ST["statement(customer)"] -.->|calls| BS["build_statement"]
ST -.->|calls| FT["format_text"]
BS -.->|calls| HC["hire_cents"]
BS -.->|calls| DC["deposit_cents"]
BS -.->|calls| DE["describe<br/>private to v3.cpp"]
FT -.->|calls| MO["money"]
QU["quote(tool, days)<br/>FR-6"] -.->|calls| HC
QU -.->|calls| DC
QU -.->|calls| DE
QU -.->|calls| MO
DE -.->|calls| CN["category_name"]

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

main.cpp
// kim hires a drill for 3 days, a ladder for 9, and the mini digger
// for 1 (the Tools and Customer are set up just above this snippet).
std::cout << v3::statement(kim);
// All three versions are kept, in namespaces v1, v2 and v3, so they
// can be compared: `same` is true only if all three strings are equal.
const bool same = v1::statement(kim) == v3::statement(kim) &&
v2::statement(kim) == v3::statement(kim);
std::cout << "all three versions agree: " << (same ? "yes" : "no") << '\n';
// The new feature. A 7-day drill hire is charged as 5 days, plus the
// power-tool deposit; a 1-day ladder hire has no deposit.
std::cout << "quotes:\n";
std::cout << " " << v3::quote(drill, 7) << '\n';
std::cout << " " << v3::quote(ladder, 1) << '\n';
Expected output
Hire statement for Kim
drill (power), 3 days: 45.00
ladder (hand), 9 days: 56.00
mini digger (heavy), 1 day: 240.00
Hire total: 341.00
Deposits (refundable): 50.00
Amount due: 391.00
all three versions agree: yes
quotes:
drill (power), 7 days: 75.00 plus 50.00 refundable deposit
ladder (hand), 1 day: 8.00

Once the rules had names, they could be tested one by one:

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

test_statement.cpp
// After step 2 the rules have names, so they can be tested one by one.
// LLD_CHECK(condition) fails if the condition is false.
// {ladder, 6} is a Hire built on the spot: the ladder for 6 days.
// 6 days is under a week: 6 charged. 7 is one week: 5 charged. 15 is two
// weeks and a day: 5 + 5 + 1 = 11 charged.
LLD_TEST(a_full_week_costs_five_days) {
LLD_CHECK_EQ(v3::hire_cents({ladder, 6}), 6 * 800);
LLD_CHECK_EQ(v3::hire_cents({ladder, 7}), 5 * 800);
LLD_CHECK_EQ(v3::hire_cents({ladder, 15}), 11 * 800);
}
// 1 day of heavy equipment is charged as 2; 3 days are above the minimum,
// so 3 are charged.
LLD_TEST(heavy_equipment_is_charged_for_at_least_two_days) {
LLD_CHECK_EQ(v3::hire_cents({digger, 1}), 2 * 12000);
LLD_CHECK_EQ(v3::hire_cents({digger, 3}), 3 * 12000);
}
LLD_TEST(only_power_tools_take_a_deposit) {
LLD_CHECK_EQ(v3::deposit_cents({drill, 1}), 5000);
LLD_CHECK_EQ(v3::deposit_cents({ladder, 1}), 0);
LLD_CHECK_EQ(v3::deposit_cents({digger, 1}), 0);
}
// After step 3 the numbers can be checked without parsing text.
// std::size_t{3} gives 3 the same type as size(), so the two compare
// without a signed/unsigned warning. 34100 = 4500 + 5600 + 24000.
LLD_TEST(the_statement_numbers_add_up) {
const v3::Statement statement = v3::build_statement(kim());
LLD_CHECK_EQ(statement.lines.size(), std::size_t{3});
LLD_CHECK_EQ(statement.hire_total_cents, 34100);
LLD_CHECK_EQ(statement.deposit_total_cents, 5000);
}
// Step 4: the new feature uses the same rules: the week rule and deposit
// for the drill (5 x 15.00 = 75.00), the heavy minimum for the digger
// (2 x 120.00 = 240.00), and the same refusal of a 0-day hire.
LLD_TEST(a_quote_uses_the_statement_rules) {
LLD_CHECK(v3::quote(drill, 7) == "drill (power), 7 days: 75.00 plus 50.00 refundable deposit");
LLD_CHECK(v3::quote(digger, 1) == "mini digger (heavy), 1 day: 240.00");
LLD_CHECK_THROWS(v3::quote(ladder, 0), std::invalid_argument);
}

Look at what each kind of test is good for. The pinned statement would catch any change to the output during steps 2 and 3. The unit tests say which rule is broken when something fails, and they test cases the pin does not reach, such as a 15-day hire (two weeks and a day, charged as 11 days) and a three-day heavy hire, where the minimum does not apply.

  • All three versions are kept side by side in namespaces v1, v2, and v3 so that you can compare them, and the pin checks all three. In real code, you edit one version in place, and version control keeps the history.
  • Each step here is one large edit. In practice, step 2 would be four or five smaller steps (extract money, run the tests; extract deposit_cents, run the tests; and so on), each small enough to undo without thinking.
  • money assumes the amount is not negative. A refund of 0.50 would be printed as 0.-50. No requirement mentions refunds today; if one arrives, money is the one place to change.
  • The shop’s prices are written in the code. A real shop would load them from a file or a database, which would add the seam the dependency inversion page describes.

The steps on this page came from the two requests, not from a list of principles. The same loop works on any code:

  1. Name the change you need to make. “Add a quote” or “expose the totals”. If there is no change, there is usually no reason to refactor: code that works and does not need to change can stay ugly.
  2. Pin the behaviour of the code you will touch, if no test already does.
  3. Find what makes the change hard. A rule you would have to copy, a value you cannot get at, a function you cannot test alone.
  4. Take the smallest step that removes that difficulty, and run the tests. Name the principle afterwards if it helps you explain the step; it should not be the reason for the step.
  5. Repeat until the change is easy, then make the change as its own step, with new tests.
  6. Stop. When the change you needed is done and the code is easy to read, further steps are speculation.
  • Extract to free functions first. In C++, a function in a namespace that takes a const Hire& is the smallest unit you can extract. It needs no object and no constructor, and it can be tested on its own. Make it a member later if it turns out to need state.
  • Keep helpers out of the header. describe is used only inside v3.cpp, so it lives in an unnamed namespace there. Code outside the file cannot call it, and changing it does not make other files recompile.
  • Return values, not output parameters. build_statement returns a Statement by value. The vector inside is moved or the copy is elided, so this is cheap, and the caller owns the result with no lifetime questions.
  • category_name returns std::string_view into string literals, which live for the whole program, so the view can never dangle. A view into a local std::string would dangle as soon as the function returned.
  • Money in whole cents. All amounts are long long cents, never double, so 0.10 + 0.20 is exactly 0.30. days * hire.tool.daily_rate_cents converts days to long long before multiplying, so it does not overflow at int’s size.
  • snprintf into a fixed buffer never writes past the buffer; if the text is too long, it is cut short. Here that cannot happen: the longest long long amount, 92233720368547758.07, is 20 characters, and the buffer holds 32. std::format (C++20) is a clearer alternative where your standard library supports it.
  • if with an initializer (if (const long long deposit = ...; deposit > 0)) keeps deposit scoped to the one place that uses it.
You gain You pay
Each rule has one home, so a price change is one edit More functions to find: a reader jumps between them
The quote and the statement cannot disagree The functions are now shared, so a change must suit both callers
Numbers can be tested and used without parsing text One more type, Statement, to name and keep in step with the output
Small steps, each checked: mistakes are cheap to undo More steps than one big edit, and the pin to write first
  • Refactoring and changing behaviour in the same step. When a test fails, you cannot tell which change broke it.
  • Refactoring without a test. The first steps feel safe; the fifth is where a rule gets lost.
  • Treating the characterization test as the specification. It records what the code does, bugs included. When you find a bug, fix it in its own step and change the pinned text on purpose, with a note saying why.
  • Refactoring code that nobody needs to change. It costs time, risks bugs, and buys nothing until someone needs to change it.
  • Applying every principle you know. Each step should remove a difficulty you have. A hierarchy of tool categories, a statement formatter interface, and a pricing strategy would each be a pattern with no problem to solve.
  • Not stopping. Once the change is easy, the next refactoring step needs a new reason.

A new category, “garden”, with a 20.00 deposit. Add garden to Category. With -Wall, the compiler warns at the switch in category_name. It does not warn at the comparisons in hire_cents and deposit_cents, so you must find deposit_cents by reading, and turn its comparison into a switch while you are there. This is the gap described in the step not taken, now with a reason to close it.

Show amounts with a currency symbol: £45.00. Change money. That is the whole change, because step 2 gave the money format one home. In the first version it was four edits.

Email the statement as HTML. Add format_html(const Statement&). build_statement does not change, and the text format does not change. This is what step 3 bought.

Exercise: Plan a four-step refactoring

A library sends an email for each overdue loan. The code below works and has run for years:

struct Loan {
std::string title;
std::string member; // an email address
bool child_member;
int days_late;
};
// Sends one email for each loan that is late enough to owe a fine.
void overdue_report(const std::vector<Loan>& loans, Mailer& mailer) {
for (const Loan& loan : loans) {
if (loan.days_late <= 0) {
continue; // not late: skip to the next loan
}
int days = loan.days_late;
if (loan.child_member) {
days -= 3; // three days' grace for children
if (days <= 0) {
continue;
}
}
int fine = days * 25; // 25 cents a day
if (fine > 500) {
fine = 500; // capped at 5.00
}
// Cents as "units.cents" text, for example 125 -> "1.25".
char money[16];
std::snprintf(money, sizeof money, "%d.%02d", fine / 100, fine % 100);
// \" is a double quote inside a string literal, so the title is
// shown in quotes.
mailer.send(loan.member, "\"" + loan.title + "\" is " +
std::to_string(loan.days_late) + " days late. Fine: " +
money + "\n");
}
}

Mailer sends real email. The library now wants the self-service screen to show the fine a member would pay when they return a book, before they return it.

  1. What makes this change hard today? Name at least three things.
  2. Before you change anything, what would you pin, and with which inputs? What makes pinning this function harder than pinning the statement on this page?
  3. Plan four steps, in order. For each, say what it changes, whether it is a refactoring or a feature, and how you would know it worked.
  4. Name one principle you would deliberately not apply, and why.
Show the explained answer

1. The fine rules (grace period, daily rate, cap) are inside the email loop, so the screen would have to copy them. The function sends email itself, so it cannot run without a mail server or without sending mail. The money format is written inline. There is no way to get a fine as a number.

2. Pin the emails the function sends. Because it sends them through Mailer, the first move is to make it possible to capture them: if Mailer is a concrete class, introduce a small interface for sending (the boundary to the email system, which earns an interface on its own) and pass a recording fake in the test. That one change is the only edit made before any test exists, so keep it mechanical: change the parameter type and nothing else, and let the compiler confirm every caller still builds. Inputs that reach every rule: an adult 4 days late (1.00); a child 5 days late (grace, 0.50); a child 2 days late (no email at all); an adult 40 days late (capped at 5.00); a loan that is not late (no email). Also pin the plural: the message says “1 days late” for a one-day loan today. That is a bug, and the pin keeps it until you decide to fix it in its own step.

3. One reasonable plan:

  1. Refactoring: extract int fine_cents(const Loan&) holding the grace period, the rate, and the cap, returning 0 when nothing is owed. The pin passes unchanged.
  2. Refactoring: extract std::string money(int cents). The pin passes unchanged. Add unit tests for fine_cents now that it has a name: the grace boundary, the cap boundary, not late.
  3. Refactoring: separate deciding what to send from sending it: std::vector<Notice> overdue_notices(loans) returns who gets which message, and overdue_report sends each notice. The pin passes, and the notices can be tested without a mailer.
  4. Feature: the self-service screen calls fine_cents (and money to show it), with new tests. The pin still passes.

Fixing “1 days” is a fifth step: a behaviour change, with the pinned text changed on purpose.

4. For example: do not make a FinePolicy interface with AdultFinePolicy and ChildFinePolicy. The two kinds of member differ by one rule (the grace period), no request asks for another kind, and a boolean on Loan already says which applies. If the library later added several member types, each with different rates and caps, that would be the time to revisit it.

  • Refactoring changes structure, not behaviour. Keep it apart from adding features, so that every failing test points at one step.
  • Pin first. A characterization test records what the code does today, bugs included, for inputs chosen to reach every rule.
  • Let a real change choose the steps. Find what makes the change hard, remove that, and run the tests. The principles explain the steps; they do not choose them.
  • Here, single responsibility and DRY gave each rule one home, separation of concerns split computing from writing, and then the quote was six lines.
  • Principles conflict. Open/closed asked for a class per category; keeping it simple won, because nothing was asking for new categories.
  • Stop when the change is easy and the code reads well.