Identify the design smell
What you will learn on this page
Section titled “What you will learn on this page”- How to name the main design smell in short C++ code you have not seen before, using the names from Anti-patterns, design smells, and design debt.
- How to justify the name with a concrete change or mistake that the code makes likely, instead of with a rule.
- How to propose a refactoring that removes the smell and to check what the refactoring itself costs.
- When the smell is acceptable and the code is better left alone.
How to use this page
Section titled “How to use this page”There are eight snippets below. Each one comes from a different small program, and each has one main smell. Some have a second one too; the answers say so. The snippets were compiled with GCC and Clang with this site’s warning flags, so none of the problems is a compile error. They are all about how hard the code is to change, or how easy it is to misuse.
For each snippet:
- Read the code and the short story above it. Then stop, and write
three things on paper or in a text file before you open the answer:
- Which smell? Name it. If you think there are two, name the one that does the most harm first.
- What harm? Describe one concrete change or one mistake that this code makes likely. “It breaks the single responsibility principle” is not an answer; “adding a third format means editing five places” is.
- What refactoring? Say what you would move, rename, or replace, and what the code would look like after it.
- Open “Show the explained answer” and compare. The answer names the main smell, explains why it hurts in this code, shows the reworked version, and ends with other fair answers, and with when the smell would be acceptable.
- If you missed a smell, reread its section of the lesson, linked in the answer.
These are the three questions from the lesson’s three questions for every smell: what change does it make harder, how often does that change happen, and what does the fix cost. A smell is evidence, not a verdict. An answer that says “this is a smell, but here it costs nothing, so leave it” can be the right one, if the reason is real.
Naming a smell is a judgement, not a fact. Where two names fit, both are accepted, as long as you can point to the lines that show it and the change it makes harder. This page checks nothing and records nothing: your answers stay on your paper.
The flawed code is labelled as flawed, and its comments say what each line does, not what is wrong with it. The reworked code is compiled and, except for one sketch, tested.
Snippet 1: a library’s late fee
Section titled “Snippet 1: a library’s late fee”A library charges a fee for each day a book is late, up to a cap. The desk and the self-service kiosk were written by different people.
Exercise: Find the smell in the late fee
Flawed (intentional)Demonstrates a mistake on purpose. Do not copy it; see the corrected version.
// FLAWED (exercise: find the problem; do not copy).// The fee for a library book returned late, in pounds. Both days are whole// days counted from the day the library opened. fee_per_day and max_fee are// in pounds too.inline double late_fee(int due_day, int returned_day, double fee_per_day, double max_fee) { if (returned_day <= due_day) { return 0.0; // on time or early: no fee } // An int times a double gives a double: days late times the daily fee. const double fee = (returned_day - due_day) * fee_per_day; return fee < max_fee ? fee : max_fee; // never more than the cap}
// Two callers, in two other files. Both compile without a warning.inline double fee_at_desk(int due_day, int today) { return late_fee(due_day, today, 0.25, 5.00);}
inline double fee_at_kiosk(int due_day, int today) { return late_fee(today, due_day, 5.00, 0.25);}Which smell or smells do you see, what harm do they do here, and what refactoring would you make?
Show the explained answer
Main smell: primitive obsession. Two days, a daily fee, and a cap are
all bare int and double values. What each number means, and in which
unit, lives only in the parameter names and a comment.
Why it hurts here. The kiosk passes both pairs the wrong way round,
and the compiler cannot notice, because an int is an int. A scratch
program run on this machine shows the result. With the book due on day
10 and returned on day 13, the desk charges 0.75 and the kiosk charges 0.
With the book returned early, on day 10 when it was due on day 13, the
kiosk charges 0.25. The kiosk bills early returns and lets late ones go
free, and a test of late_fee alone would still pass. Money as a double
is a second problem: 0.10 a day for 3 days comes out as
0.30000000000000004, not 0.30, so the totals in a report can be off by
fractions of a penny that someone then has to explain.
The refactoring. Give each value a type that says what it is, as in the lesson’s smell 1:
VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// Money as a whole number of pence: exact, and not a bare number. Braces// refuse a double, so Pence{0.25} does not compile.struct Pence { std::int64_t value = 0; friend auto operator<=>(const Pence&, const Pence&) = default;};
// A day, counted from the day the library opened.struct LibraryDay { int value = 0; friend auto operator<=>(const LibraryDay&, const LibraryDay&) = default;};
// The two amounts that always travel together, named at the call site.struct FeeRule { Pence per_day; Pence cap;};
// The loan knows its own due day, so a caller cannot pass it in the wrong// place: the second argument is a plain day, the first a Loan.struct Loan { LibraryDay due;};
inline Pence late_fee(const Loan& loan, LibraryDay returned, const FeeRule& rule) { if (returned <= loan.due) { return Pence{0}; // on time or early: no fee } const std::int64_t days_late = returned.value - loan.due.value; return Pence{std::min(days_late * rule.per_day.value, rule.cap.value)};}
// The library's one rule. Designated initialisers name each amount.inline constexpr FeeRule standard_rule{.per_day = Pence{25}, .cap = Pence{500}};
inline Pence fee_at_desk(const Loan& loan, LibraryDay today) { return late_fee(loan, today, standard_rule);}- Money is a whole number of pence in its own type, so it is exact.
Because
Penceis built with braces,Pence{0.25}is a narrowing conversion and does not compile. - The due day moved into a
Loan. The two days are no longer two arguments of the same type, so the kiosk’s swap is a compile error: the first argument must be aLoan. The tests check both of these at compile time. - The daily fee and the cap always travel together, so they became one
FeeRule, written with designated initialisers that name each amount. That also removes a small data clump.
The tests check the fee on time, after three days, at the cap, and past the cap. The page on strong types goes further, with money types that allow only the operations that make sense.
Other fair answers. “Long parameter list” is fair: four parameters, two pairs of the same type, is exactly the shape that gets swapped. “Data clump” for the fee and the cap is fair too. The fix is the same.
When it would be acceptable. A one-off script that works out this
month’s fees once, run by the person who wrote it, does not need four
new types. Inside one small function, a local int days_late is fine:
the smell is about values that cross function boundaries, where the
next caller cannot see what each number means.
Snippet 2: a school report card
Section titled “Snippet 2: a school report card”A school prints a report card with one line for each student. The printer was written first; the class-list screen and a parents’ email are planned next.
Exercise: Find the smell in the report-card printer
Flawed (intentional)Demonstrates a mistake on purpose. Do not copy it; see the corrected version.
// FLAWED (exercise: find the problem; do not copy).// A student's results for one course: plain data, with no functions.struct Student { std::string name; std::vector<int> marks; // each from 0 to 100 bool resit = false; // on a resit, the average counts as 40 at most};
// Prints one line of a school's report card for each student.class ReportCardPrinter {public: explicit ReportCardPrinter(std::string school) : school_(std::move(school)) {}
[[nodiscard]] std::string heading() const { return school_ + " report card"; }
// "Ana: 62 pass". Every value here comes from the student. [[nodiscard]] std::string line_for(const Student& student) const { int average = 0; if (!student.marks.empty()) { int sum = 0; for (const int mark : student.marks) { sum += mark; } // Integer division: the average is rounded down. average = sum / static_cast<int>(student.marks.size()); } if (student.resit && average > 40) { average = 40; } const bool passed = average >= 40; return student.name + ": " + std::to_string(average) + (passed ? " pass" : " fail"); }
private: std::string school_;};Which smell or smells do you see, what harm do they do here, and what refactoring would you make?
Show the explained answer
Main smell: feature envy. line_for belongs to the printer, but it
reads the student’s name, marks, and resit flag, and nothing of the
printer’s own. It works out the
average and the pass rule, which are facts about the student’s results,
not about printing.
Why it hurts here. The class-list screen and the parents’ email both need the average and pass or fail. There is nowhere to get them except inside a printing function, so each one will copy the loop, the rounding, and the resit cap. When the school changes the rule, for example to round to the nearest mark, or to cap a resit at 50, someone has to find every copy, and the one they miss shows a parent a different result from the report card. The lesson’s smell 2 shows exactly that drift between two copies of an order total.
The refactoring. Move the calculation to where the data is:
VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// A student's results for one course. The rules about marks live here, next// to the marks, so every screen that needs an average asks for it.class Student {public: // Throws std::invalid_argument for a mark outside 0 to 100. Student(std::string name, std::vector<int> marks, bool resit) : name_(std::move(name)), marks_(std::move(marks)), resit_(resit) { for (const int mark : marks_) { if (mark < 0 || mark > 100) { throw std::invalid_argument("a mark must be from 0 to 100"); } } }
[[nodiscard]] const std::string& name() const { return name_; }
// Rounded down; 0 with no marks; at most 40 on a resit. [[nodiscard]] int average() const { if (marks_.empty()) { return 0; } int sum = 0; for (const int mark : marks_) { sum += mark; } const int average = sum / static_cast<int>(marks_.size()); return resit_ && average > 40 ? 40 : average; }
[[nodiscard]] bool passed() const { return average() >= 40; }
private: std::string name_; std::vector<int> marks_; bool resit_;};
class ReportCardPrinter {public: explicit ReportCardPrinter(std::string school) : school_(std::move(school)) {}
[[nodiscard]] std::string heading() const { return school_ + " report card"; }
// Layout only: what to print, not how a result is worked out. [[nodiscard]] std::string line_for(const Student& student) const { return student.name() + ": " + std::to_string(student.average()) + (student.passed() ? " pass" : " fail"); }
private: std::string school_;};Studentbecame a class that owns its marks and answersaverage()andpassed(). It also checks, once, that each mark is from 0 to 100, which the plain struct never did.- The printer is left with what is really its own: the school’s name and the layout of a line.
- The tests check the rounding down, the resit cap, a student with no marks, the printed lines, and that a mark of 101 is refused.
This is the step put each rule where its data is from the modeling lessons, applied after the fact.
Other fair answers. Seen from the other side, Student is a plain
data class: data with no behaviour, so its rules have nowhere to
live. That is the same problem, and the same fix.
When it would be acceptable. If Student is a record read from a
file or a database and many programs share its layout, you may not be
able to give it functions. Then a free function average(const Student&)
next to the struct, in the same header, is a good middle way: one home
for the rule, outside the printer. And if the printer really is the only
place that will ever need an average, the envy costs little today; the
planned screen and email are what make it worth fixing now.
Snippet 3: a password rule
Section titled “Snippet 3: a password rule”A small web app checks passwords in four places. The product owner asks for the minimum length to go from 8 characters to 12.
Exercise: Find the smell in the password checks
Flawed (intentional)Demonstrates a mistake on purpose. Do not copy it; see the corrected version.
// FLAWED (exercise: find the problem; do not copy).// Four functions from four files of one web app. Each is short and correct// on its own.
// signup.cpp: a new account. Returns a message to show, or nothing if the// password is accepted.inline std::optional<std::string> signup_problem(const std::string& password) { if (password.size() < 8) { return "Your password must be at least 8 characters."; } return std::nullopt; // accepted}
// settings.cpp: a user changing their own password.inline bool can_change_password(const std::string& old_password, const std::string& new_password) { return new_password != old_password && new_password.length() >= 8;}
// import.cpp: accounts loaded from a spreadsheet by an administrator.inline bool import_row_accepted(const std::string& email, const std::string& password) { return email.find('@') != std::string::npos && password.size() > 7;}
// help.cpp: the text beside every password box.inline const std::string password_help = "Use 8 or more characters, including at least one digit.";Which smell or smells do you see, what harm do they do here, and what refactoring would you make?
Show the explained answer
Main smell: shotgun surgery. One business rule, “a password has at least 8 characters”, is spread over four files. One change to the rule means small edits in all of them.
Why it hurts here. The change to 12 needs four edits, and nothing
tells you that there are four. Each is written differently, which makes
them hard to search for: size() < 8, length() >= 8, size() > 7, and
the number 8 inside a sentence. A search for 8 finds three of them and
misses the import, which says > 7. Miss the import, and an administrator can still load
accounts with 8-character passwords after the rule says 12. The rule has
already drifted once: the help text promises “at least one digit”, and
no code checks for a digit.
The refactoring. Gather the rule into one place that both checks a password and describes the rule, as in the lesson’s smell 3:
VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// The one home for the password rule. A change to the length, or a new// rule, is made here and nowhere else.struct PasswordPolicy { std::size_t min_length = 8; bool needs_digit = true;
// A message for the first rule the password breaks, or nothing. [[nodiscard]] std::optional<std::string> problem(const std::string& password) const { if (password.size() < min_length) { return "Your password must be at least " + std::to_string(min_length) + " characters."; } // std::isdigit needs an unsigned char value, hence the cast. const auto is_digit = [](char c) { return std::isdigit(static_cast<unsigned char>(c)); }; if (needs_digit && std::none_of(password.begin(), password.end(), is_digit)) { return std::string("Your password must include at least one digit."); } return std::nullopt; }
// The help text is made from the same numbers, so it cannot drift. [[nodiscard]] std::string help() const { return "Use " + std::to_string(min_length) + " or more characters" + (needs_digit ? ", including at least one digit." : "."); }};
inline constexpr PasswordPolicy site_policy{};
inline std::optional<std::string> signup_problem(const std::string& password) { return site_policy.problem(password);}
inline bool can_change_password(const std::string& old_password, const std::string& new_password) { return new_password != old_password && !site_policy.problem(new_password);}
inline bool import_row_accepted(const std::string& email, const std::string& password) { return email.find('@') != std::string::npos && !site_policy.problem(password);}PasswordPolicyis the one home for the rule. Going to 12 is one edit, tomin_length.- The help text is built from the same fields, so it cannot promise a
rule the code does not check. The digit rule is now real, which is a
change in behaviour, not only a refactoring: the old signup accepted
abcdefgh, and the new one refuses it. A real team would agree that change with the product owner first. - The three call sites still exist, but they ask the policy instead of knowing the rule. The tests check each message, the help text, and a policy with different settings.
The principle behind it is DRY: one home for each piece of knowledge.
Other fair answers. “Duplicated knowledge” (DRY) is the same problem seen from the code, rather than from the change. “Magic number” for the bare 8 is also fair.
When it would be acceptable. Only if the four rules are genuinely different knowledge that happens to share a number today. If the import had its own rule, for example because imported accounts must reset their password at first login, then forcing it through the same policy would be the wrong abstraction. Ask the product owner whether the four places must always agree. Here they must.
Snippet 4: exporting a shop’s sales
Section titled “Snippet 4: exporting a shop’s sales”A shop exports its sales as a readable list for the end of the day and as comma-separated values for the accountant. Look at the two callers first.
Exercise: Find the smell in the sales export
Flawed (intentional)Demonstrates a mistake on purpose. Do not copy it; see the corrected version.
// FLAWED (exercise: find the problem; do not copy).struct Sale { std::string item; std::int64_t cents = 0;};
// Writes a shop's sales to out, as text or as comma-separated values.inline void export_sales(std::ostream& out, const std::vector<Sale>& sales, bool csv, bool with_total, bool newest_first) { std::vector<Sale> rows = sales; // a copy, so the caller's order is kept if (newest_first) { std::reverse(rows.begin(), rows.end()); // sales are stored oldest first } std::int64_t total = 0; for (const Sale& sale : rows) { total += sale.cents; if (csv) { out << sale.item << ',' << sale.cents << '\n'; } else { out << sale.item << ": " << sale.cents << " cents\n"; } } if (with_total) { out << (csv ? "total," : "Total: ") << total << (csv ? "\n" : " cents\n"); }}
// Two callers.inline void end_of_day(std::ostream& out, const std::vector<Sale>& sales) { export_sales(out, sales, false, true, true);}
inline void accounts_feed(std::ostream& out, const std::vector<Sale>& sales) { export_sales(out, sales, true, false, false);}Which smell or smells do you see, what harm do they do here, and what refactoring would you make?
Show the explained answer
Main smell: flag arguments. Three bool parameters choose what the
function does. At the call site, export_sales(out, sales, false, true, true)
says nothing about which choice is which.
Why it hurts here. To check the end-of-day caller, a reader has to
open the function and count parameters. Swapping two of the bool
arguments still compiles, and gives a report in the wrong order or
without a total, which nobody may notice for weeks. Each new choice, such
as “only today’s sales”, adds a fourth bool and changes every call.
The refactoring. Give each choice a name. Here the options became one struct with a default for each, and the two-way choices that are not yes-or-no became enums:
VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
struct Sale { std::string item; std::int64_t cents = 0;};
enum class Format { text, csv };enum class SaleOrder { oldest_first, newest_first };
// Every option has a name and a default, so a caller sets only what differs.struct ExportOptions { Format format = Format::text; bool with_total = false; SaleOrder order = SaleOrder::oldest_first;};
inline void export_sales(std::ostream& out, const std::vector<Sale>& sales, const ExportOptions& options) { const bool csv = options.format == Format::csv; std::vector<Sale> rows = sales; // a copy, so the caller's order is kept if (options.order == SaleOrder::newest_first) { std::reverse(rows.begin(), rows.end()); // sales are stored oldest first } std::int64_t total = 0; for (const Sale& sale : rows) { total += sale.cents; out << sale.item << (csv ? "," : ": ") << sale.cents << (csv ? "\n" : " cents\n"); } if (options.with_total) { out << (csv ? "total," : "Total: ") << total << (csv ? "\n" : " cents\n"); }}
// Designated initialisers: each call names what it sets.inline void end_of_day(std::ostream& out, const std::vector<Sale>& sales) { export_sales(out, sales, {.with_total = true, .order = SaleOrder::newest_first});}
inline void accounts_feed(std::ostream& out, const std::vector<Sale>& sales) { export_sales(out, sales, {.format = Format::csv});}- A call such as
export_sales(out, sales, {.with_total = true, .order = SaleOrder::newest_first})reads as what it asks for. Designated initialisers must follow the order of the fields, and a field left out takes its default. - A new option is a new field with a default, so the existing calls do not change.
- The output is the same as before for both callers: the tests check the end-of-day list (newest first, with a total) and the accountant’s feed (oldest first, no total) against the exact text that the flawed version printed in a scratch run.
The lesson’s smell 4 uses enums for every flag, and the page on strong types explains the choice between the two. Both are good answers.
Other fair answers. Splitting the function by format, into
write_sales_text and write_sales_csv, is a good alternative: the
two formats share only the loop. “Long parameter list” is fair as a
second smell.
When it would be acceptable. A single bool whose meaning is clear
from the function name, such as set_visible(true), is not a smell.
A private helper with one caller next to it, where the reader sees the
call and the definition together, costs little too.
Snippet 5: can this driver take the trip?
Section titled “Snippet 5: can this driver take the trip?”A ride-hailing dispatcher checks whether a driver may take a trip: not suspended, insured for paying passengers on the day, and with enough seats.
Exercise: Find the smell in the trip check
Flawed (intentional)Demonstrates a mistake on purpose. Do not copy it; see the corrected version.
// FLAWED (exercise: find the problem; do not copy).// A calendar date. The defaulted <=> compares year, then month, then day.struct Date { int year = 0; int month = 0; int day = 0; friend auto operator<=>(const Date&, const Date&) = default;};
class Insurance {public: Insurance(Date expires, bool covers_passengers) : expires_(expires), covers_passengers_(covers_passengers) {} [[nodiscard]] Date expires() const { return expires_; } [[nodiscard]] bool covers_passengers() const { return covers_passengers_; }
private: Date expires_; bool covers_passengers_;};
class Vehicle {public: Vehicle(int seats, Insurance insurance) : seats_(seats), insurance_(insurance) {} [[nodiscard]] int seats() const { return seats_; } [[nodiscard]] const Insurance& insurance() const { return insurance_; }
private: int seats_; Insurance insurance_; // owned by value};
class Driver {public: Driver(Vehicle vehicle, bool suspended) : vehicle_(vehicle), suspended_(suspended) {} [[nodiscard]] const Vehicle& vehicle() const { return vehicle_; } [[nodiscard]] bool suspended() const { return suspended_; }
private: Vehicle vehicle_; // owned by value bool suspended_;};
// In the dispatcher: may this driver take a trip for this many passengers?inline bool may_take(const Driver& driver, Date today, int passengers) { return !driver.suspended() && driver.vehicle().insurance().expires() >= today && driver.vehicle().insurance().covers_passengers() && driver.vehicle().seats() >= passengers;}Which smell or smells do you see, what harm do they do here, and what refactoring would you make?
Show the explained answer
Main smell: message chains. driver.vehicle().insurance().expires()
walks from the driver to their vehicle to its insurance. The dispatcher
has to know how all three classes are connected, not only what it wants
to know.
Why it hurts here. Suppose the insurance moves from the vehicle to the driver, because a new law insures the person, not the car, or a driver may now have two vehicles. Every chain like this one, in the dispatcher and in any code that copied it, breaks and must be rewritten, though none of them cares where the insurance is kept. The rule for “insured on the day” is also out in the dispatcher: is the last day included? Another caller may decide differently.
The refactoring. Ask, do not reach. Each class answers a question about its own data:
VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
struct Date { int year = 0; int month = 0; int day = 0; friend auto operator<=>(const Date&, const Date&) = default;};
class Insurance {public: Insurance(Date expires, bool covers_passengers) : expires_(expires), covers_passengers_(covers_passengers) {} // Valid on its last day, and covering paying passengers. [[nodiscard]] bool covers_trip_on(Date day) const { return covers_passengers_ && day <= expires_; }
private: Date expires_; bool covers_passengers_;};
class Vehicle {public: Vehicle(int seats, Insurance insurance) : seats_(seats), insurance_(insurance) {} [[nodiscard]] bool can_carry(int passengers, Date day) const { return passengers <= seats_ && insurance_.covers_trip_on(day); }
private: int seats_; Insurance insurance_;};
class Driver {public: Driver(Vehicle vehicle, bool suspended) : vehicle_(vehicle), suspended_(suspended) {} [[nodiscard]] bool may_take(int passengers, Date day) const { return !suspended_ && vehicle_.can_carry(passengers, day); }
private: Vehicle vehicle_; bool suspended_;};
// The dispatcher now knows only drivers.inline bool may_take(const Driver& driver, Date today, int passengers) { return driver.may_take(passengers, today);}Insurancedecides whether it covers a trip on a day, including the rule that it is valid on its last day.Vehicledecides whether it can carry the passengers, and asks its own insurance.Driveradds the suspension rule and asks its own vehicle. The dispatcher asks the driver one question.- The getters that only served the chain are gone. The tests check a valid trip on the last day of cover, and each reason for a refusal: expired, too few seats, suspended, and cover that excludes passengers.
This is the Law of Demeter and the lesson’s smell 5.
Other fair answers. “Feature envy” is fair: may_take in the
dispatcher uses only the driver’s data. Moving it into Driver fixes
both.
When it would be acceptable. A chain through plain data is not this
smell. Reading settings.network.port from a configuration struct, or a
fluent builder whose every call returns the same builder, does not
expose a design that might change. The test is how much the caller has
to know, not how many dots there are; see
when the law does not apply.
Pushing every question down also has a cost: a Driver with forty
forwarding functions is worse than one chain.
Snippet 6: writing a CSV file
Section titled “Snippet 6: writing a CSV file”A small helper writes comma-separated values to a stream. Read the caller at the bottom as if you were reviewing it.
Exercise: Find the smell in the CSV writer
Flawed (intentional)Demonstrates a mistake on purpose. Do not copy it; see the corrected version.
// FLAWED (exercise: find the problem; do not copy).// Writes comma-separated values to a stream that someone else owns.class CsvWriter {public: void open(std::ostream& out) { out_ = &out; } void set_columns(std::vector<std::string> names) { columns_ = std::move(names); } void write_header() { write_line(columns_); } void write_row(const std::vector<std::string>& cells) { write_line(cells); }
private: void write_line(const std::vector<std::string>& cells) { for (std::size_t i = 0; i < cells.size(); ++i) { if (i > 0) { *out_ << ','; // a comma between cells, not before the first } *out_ << cells[i]; // *out_ is the stream that open was given } *out_ << '\n'; }
std::ostream* out_ = nullptr; // null until open; used, not owned std::vector<std::string> columns_;};
// A caller, written months later by someone else.inline void export_members(std::ostream& out) { CsvWriter writer; writer.open(out); writer.write_header(); writer.set_columns({"name", "email"}); writer.write_row({"Ana", "ana@example.com"}); writer.write_row({"Ben"});}Which smell or smells do you see, what harm do they do here, and what refactoring would you make?
Show the explained answer
Main smell: temporal coupling. The calls must come in one order,
open, then set_columns, then write_header, then the rows, and
nothing in the class says so or checks it.
Why it hurts here. The caller calls write_header before
set_columns, which compiles and runs. A scratch run on this machine
printed an empty line, then the two rows, and no header at all. The
second row has one cell instead of two, and that goes through too. A
caller who forgets open is worse: write_line then writes through a
null pointer, which is undefined behaviour, typically a crash. The order
can only be learned by reading the class, and each new caller is a new
chance to get it wrong.
The refactoring. Make the wrong order impossible to write: everything the object needs comes into the constructor, as in the lesson’s smell 6:
VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
class CsvWriter {public: // Everything the writer needs comes in at once, so there is no // half-ready writer. Throws std::invalid_argument for no columns. CsvWriter(std::ostream& out, std::vector<std::string> columns) : out_(&out), columns_(std::move(columns)) { if (columns_.empty()) { throw std::invalid_argument("a CSV file needs at least one column"); } write_line(columns_); // the header, always first, exactly once }
// Throws std::invalid_argument, and writes nothing, for a row whose // number of cells is not the number of columns. void write_row(const std::vector<std::string>& cells) { if (cells.size() != columns_.size()) { throw std::invalid_argument("a row needs one cell for each column"); } write_line(cells); }
private: void write_line(const std::vector<std::string>& cells) { for (std::size_t i = 0; i < cells.size(); ++i) { if (i > 0) { *out_ << ','; } *out_ << cells[i]; } *out_ << '\n'; }
std::ostream* out_; // never null; used, not owned std::vector<std::string> columns_;};
inline void export_members(std::ostream& out) { CsvWriter writer(out, {"name", "email"}); writer.write_row({"Ana", "ana@example.com"});}- A
CsvWritercannot exist without a stream and its columns, so there is no “not open yet” state, and the pointer is never null. - The constructor writes the header, so it is always first and written exactly once.
- A row of the wrong width throws
std::invalid_argumentand writes nothing. The tests check the output, that the short row is refused, and that a writer with no columns is refused. - The writer still keeps a pointer to a stream it does not own, so the stream must outlive it. That rule is now the only one left for a caller to know, and the header comment says it.
This is the same idea as RAII: a valid object from the moment it exists.
Other fair answers. “Invalid intermediate state” or “two-phase initialisation” describe the same problem.
When it would be acceptable. Some frameworks need a default
constructor and a later init, for example a type read back from a file
field by field. Then keep the order, but check it: each function refuses
to run, or throws, when called in the wrong state. A builder whose calls
may come in any order, with one final build() that checks everything,
is not this smell.
Snippet 7: a clinic’s front desk
Section titled “Snippet 7: a clinic’s front desk”A small clinic’s front-desk program grew around one class. These are its declarations; the definitions are hundreds of lines long.
Exercise: Find the smell in the clinic system
Flawed (intentional)Demonstrates a mistake on purpose. Do not copy it; see the corrected version.
// FLAWED (exercise: find the problem; do not copy).struct Patient { std::string name; std::string phone;};
struct Appointment { int patient_id = 0; int doctor_id = 0; int start_minute = 0; // minutes since midnight on the day int day = 0; // days since the clinic opened};
// Everything the clinic's front desk does.class ClinicSystem {public: int register_patient(Patient patient); // returns the new patient's id void update_phone(int patient_id, std::string phone); int book(int patient_id, int doctor_id, int day, int start_minute); void cancel(int appointment_id); [[nodiscard]] std::int64_t amount_owed_cents(int patient_id) const; void record_payment(int patient_id, std::int64_t cents); void send_reminders(int day); // a text message to each patient seen that day [[nodiscard]] std::string monthly_report(int month) const; // ... and thirty more
private: std::map<int, Patient> patients_; // by patient id std::map<int, Appointment> appointments_; // by appointment id std::map<int, std::int64_t> owed_cents_; // by patient id std::vector<std::string> sent_messages_; int next_patient_id_ = 1; int next_appointment_id_ = 1; std::int64_t fee_per_visit_cents_ = 4'500; int reminder_hours_before_ = 24;};Which smell or smells do you see, what harm do they do here, and what refactoring would you make?
Show the explained answer
Main smell: a god class. ClinicSystem holds patients, appointments,
money, and sent messages, and has functions for all of them. Group the
member functions by the data they use and four separate jobs appear:
the patient register (patients_, next_patient_id_), the diary
(appointments_, next_appointment_id_), billing (owed_cents_,
fee_per_visit_cents_), and reminders (sent_messages_,
reminder_hours_before_).
Why it hurts here. Every change touches the same class: a new billing rule, a new reminder channel, a change to how appointments are booked. Two people working on billing and on reminders edit the same file and the same header, and every file that includes the header is rebuilt. To test that a reminder is sent, a test has to build the whole system, patients and money included. The lesson’s section on the god class describes the same shape in a delivery app.
The refactoring. Split the class along the data each group of functions uses, and keep one short function for the steps that cross the parts. This version is a sketch, declarations only: it is compiled but not run.
CompiledCompiled with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01); output not tested.
// Small id types, so a patient id cannot be passed where a doctor id goes.struct PatientId { int value = 0; };struct DoctorId { int value = 0; };struct AppointmentId { int value = 0; };struct Slot { int day = 0; int start_minute = 0; };
struct Patient { std::string name; std::string phone;};
// Who the patients are. Used by: registration, phone changes, reminders.class PatientRegistry {public: PatientId add(Patient patient); void update_phone(PatientId patient, std::string phone); [[nodiscard]] const Patient& find(PatientId patient) const; // throws if unknownprivate: std::map<int, Patient> patients_; // by PatientId value int next_id_ = 1;};
// Who sees whom, and when. Refuses a slot the doctor already has.class Diary {public: struct Entry { PatientId patient; DoctorId doctor; Slot slot; }; AppointmentId book(PatientId patient, DoctorId doctor, Slot slot); void cancel(AppointmentId appointment); [[nodiscard]] std::vector<Entry> on_day(int day) const;private: std::map<int, Entry> entries_; // by AppointmentId value int next_id_ = 1;};
// What each patient owes.class Billing {public: explicit Billing(std::int64_t fee_per_visit_cents); void charge_visit(PatientId patient); void record_payment(PatientId patient, std::int64_t cents); [[nodiscard]] std::int64_t owed_cents(PatientId patient) const;private: std::map<int, std::int64_t> owed_cents_; // by PatientId value std::int64_t fee_per_visit_cents_;};
// Sends text messages. Owns no patient data: it is told whom to message.class Reminders {public: void send(const Patient& patient, Slot slot); [[nodiscard]] const std::vector<std::string>& sent() const { return sent_; }private: std::vector<std::string> sent_;};
// The one place that knows a booking touches the diary and the bill.AppointmentId book_visit(Diary& diary, Billing& billing, PatientId patient, DoctorId doctor, Slot slot);- Each part has its own data and can be tested on its own: a
Billingtest needs no patients’ phone numbers. book_visitis the one place that knows a booking touches the diary and the bill. It borrows the parts it is given and keeps no reference to them.- The ids got small types of their own on the way, so a patient id can no longer be passed where a doctor id goes. That fixes the second smell below.
The modeling page shows how to check that each class is the right size while designing, and cohesion and coupling explains why functions that use the same data belong together.
Other fair answers. Primitive obsession is a fair second
answer: every id, day, and time is a bare int, so book(doctor, patient, ...)
with the two ids swapped compiles. “Divergent change”, one class changed
for many unrelated reasons, is the name for the symptom.
When it would be acceptable. Early in a small program, one class with a few functions is often the right start, because you do not yet know where the seams are. The smell is in the growth: once changes to different features keep colliding in one class, split it. Do the split in small steps with tests, as in safe refactoring of legacy code, not in one rewrite.
Snippet 8: showing a temperature
Section titled “Snippet 8: showing a temperature”A small wall display in a meeting room shows the room’s temperature in Celsius. Nobody has asked for any other format.
Exercise: Find the smell in the temperature display
Flawed (intentional)Demonstrates a mistake on purpose. Do not copy it; see the corrected version.
// FLAWED (exercise: find the problem; do not copy).// Formats a room sensor's temperature for a small wall display. The display// shows Celsius, and that is the only format anyone has asked for.class IReadingFormatter {public: virtual ~IReadingFormatter() = default; [[nodiscard]] virtual std::string format(double value) const = 0;};
// Unit supplies a suffix; Precision is digits after the point; ShowSign adds// a plus sign to values above zero.template <typename Unit, int Precision = 1, bool ShowSign = false>class ReadingFormatter final : public IReadingFormatter {public: [[nodiscard]] std::string format(double value) const override { std::ostringstream out; out << std::fixed << std::setprecision(Precision); // always that many digits if (ShowSign && value > 0) { out << '+'; } out << value << Unit::suffix; return out.str(); }};
struct Celsius { static constexpr const char* suffix = " C";};
enum class FormatterKind { standard };
class FormatterFactory {public: static std::unique_ptr<IReadingFormatter> create(FormatterKind kind) { switch (kind) { case FormatterKind::standard: return std::make_unique<ReadingFormatter<Celsius>>(); } return nullptr; // not reached while the enum has one value }};
// The one caller.inline std::string display_text(double celsius) { return FormatterFactory::create(FormatterKind::standard)->format(celsius);}Which smell or smells do you see, what harm do they do here, and what refactoring would you make?
Show the explained answer
Main smell: speculative generality. An interface with one implementation, a template with two parameters that nobody sets, a unit type with one value, an enum with one value, and a factory with one choice, all to print a number with one digit after the point.
Why it hurts here. A reader has to go through five types and a
switch to find the line that does the work. A real change, such as
“show one digit, but no digit for whole numbers”, lands in a template
whose other options must keep working, though nobody uses them. A heap
allocation and a virtual call happen on every update, which is small,
but buys nothing. The nullptr return after the switch is a trap for
the day someone adds a second enum value and forgets the factory.
The refactoring. Replace it with what is needed today:
VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// The wall display's text for a temperature in Celsius, with one digit after// the point: 21.0 becomes "21.0 C".inline std::string display_text(double celsius) { std::ostringstream out; out << std::fixed << std::setprecision(1) << celsius << " C"; return out.str();}The tests check that 21.0 shows as 21.0 C and that -3.46 shows as
-3.5 C. If a second format is ever asked for, the function is easy to
change, and that is the moment to decide what shape the choice should
take. The page on
the cost of abstraction works
through a larger example, and
YAGNI
is the rule behind it.
Other fair answers. “Pattern soup”, a factory with one product, from
when patterns hurt, is fair. So is
“lazy class” for the Celsius type and the factory.
When it would be acceptable. The interface earns its place if something real needs a second implementation: a test double, because tests need to control the display, or a Fahrenheit version that is scheduled, not imagined. Even then, keep only that interface, not the template options; see when building the abstraction up front is right. A library used by many teams with many units is also a different problem from this one display.
Self-check
Section titled “Self-check”After the eight snippets, check your answers against these questions, not only against the names:
- Did each answer point to the lines that show the smell, and to one concrete change or mistake it makes likely?
- Did your refactoring keep the behaviour the same where the old code was right? Snippet 3 is the one where the fix also changes behaviour, on purpose, and the answer says so.
- Did you check what your refactoring costs? A fix for one smell, overdone, is often another: pushing every question down a message chain gives forwarding functions, and an interface “for later” is snippet 8.
- Did you say when you would leave the code alone? A smell in code that nobody changes costs nothing today; the lesson’s section on when not to pay covers this.
If two of your names differ from the answers but you can show the lines and the harm, your answer is fair. If you named a smell but could not say what change it makes harder, reread the three questions.
Summary
Section titled “Summary”- A smell is evidence that a change will be harder than it should be, not a rule broken. Name it, then show the change it makes painful.
- The eight smells here were primitive obsession, feature envy, shotgun surgery, flag arguments, message chains, temporal coupling, a god class, and speculative generality.
- Each fix moved knowledge to one place: into a type, into the class that owns the data, into one policy, into named options, into the constructor, or out of code that nobody needed.
- Many snippets have a second fair answer. What matters is that the refactoring removes the harm you named, and costs less than it saves.
- Some smells are acceptable: in a one-off script, in stable code that nobody changes, or where the “duplicated” rules are really different.