Anti-patterns, design smells, and design debt
What you will learn on this page
Section titled “What you will learn on this page”- What a design smell is, how it differs from an anti-pattern, and why a smell is a question to ask, not a rule to obey.
- Six smells that appear in almost every growing C++ program, each shown in flawed and fixed code: primitive obsession, feature envy, shotgun surgery, flag arguments, message chains, and temporal coupling. For each, why it hurts, what the fix is, what the fix costs, and when the code is fine as it is.
- How to check that removing a smell changed nothing it should not.
- Where this site covers the other well-known smells: the god class, speculative generality, pattern overuse, and ownership tangles.
- What design debt is, how to record it, how to decide which debt to pay first, and when not to pay it at all.
The problem
Section titled “The problem”A food delivery app has grown for three years. Nobody designed it badly on purpose, and every part of it works. But the team has noticed that some changes cost far more than they should:
- Adding vouchers as a payment method took a week and shipped with a bug: for a month, the refund screen offered refunds on voucher payments, which cannot be refunded.
- The receipt and the checkout page show different totals for most orders from members, one cent apart.
- A new screen crashed on its first day because it used a courier before giving the courier a vehicle.
- A call in the notification code reads
notification_text(customer, false, true), and two reviewers disagreed about what it sent.
Each of these has a cause in the design, and each cause has a name. Naming it is useful for two reasons. A name lets a reviewer say “feature envy” instead of a paragraph, and each name comes with the known ways to fix it and the known ways the fix goes wrong.
Smells and anti-patterns
Section titled “Smells and anti-patterns”A design smell is a visible feature of code that often goes with a design problem. “One change needs edits in four files” is a smell. So is “this function reads five fields of another object and none of its own”. A smell is evidence, not a verdict: sometimes the four files are four genuinely different concerns, and sometimes the function rightly belongs where it is. The word fits for that reason. A smell tells you to look, not what you will find.
An anti-pattern is stronger: a solution that keeps being chosen because it looks right at first, that reliably turns out worse, and that has a known better alternative. A god class, a singleton used as a global variable, and copy-paste as a way to reuse code are anti-patterns. Most anti-patterns show up first as smells.
Most of the names on this page are those of the catalogue in Martin Fowler’s book Refactoring, whose chapter on smells was written with Kent Beck; flag argument and temporal coupling are not in its original smell catalogue, though both names are in wide use. The examples are this site’s own.
Three questions for every smell
Section titled “Three questions for every smell”Before fixing anything, ask:
- What change does this make harder, or what mistake does it make easier? If you cannot name one, there is no problem to fix.
- How often does that change, or that mistake, happen? A smell in code that nobody has touched for two years costs nothing today.
- What does the fix cost, and what does it make harder? Every fix below adds or moves structure. Some of that structure has its own cost, and the fix for one smell, overdone, is another smell.
The rest of the page applies these questions to each smell.
The example
Section titled “The example”All six smells come from the delivery app, one header each, with a
flawed and a fixed namespace side by side. Each fix is a
refactoring, so the test
for each pair runs both versions on the same inputs and requires them
to agree, wherever the flawed version was right. Where the flawed
version was wrong, the test says so. The code is compiled with GCC
and Clang and tested with and without the sanitizers.
Smell 1: primitive obsession
Section titled “Smell 1: primitive obsession”What it looks like. Values with meaning, such as money, distances,
durations, and identifiers, are passed as bare int and double,
and what each number means lives in a comment or in a parameter name:
VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// FLAWED (shown as a smell; do not copy). Every input is a bare number, and// what each one means lives only in this comment:// distance in km; minutes until the courier collects; priority 0 normal,// 1 high; basket total in dollars. Returns the fee in dollars.// Rules: free for a basket of 30 dollars or more; otherwise 2 dollars, plus// 50 cents per started km beyond the first 2 km, plus 1.50 for high// priority, plus 1 dollar if pick-up is less than 15 minutes away.// Where it goes wrong: distance and basket are both double, so a call// with the two swapped compiles silently and returns a wrong fee. The// int minutes can also take the double distance, losing its fraction,// with a warning only under -Wconversion. Priority is an int, so 2 or -1// is accepted and quietly treated as normal. The result is a double// number of dollars, which each caller rounds in its own way.inline double delivery_fee(double distance, int minutes, int priority, double basket) { // A big enough basket delivers free, whatever the other inputs say. if (basket >= 30.0) { return 0.0; } double fee = 2.0; if (distance > 2.0) { // std::ceil rounds up: 2.1 km is 0.1 km beyond the first 2, and // ceil(0.1) is 1, so it is charged as one started km. fee += 0.5 * std::ceil(distance - 2.0); // per started km } // A magic number: only 1 means high, and nothing stops a caller // from passing any other int. if (priority == 1) { fee += 1.5; } if (minutes < 15) { fee += 1.0; // a rush job } return fee;}Why it hurts. Nothing stops a caller from passing the arguments in
the wrong order. Swapping the distance and the basket total, both
double, compiles without a word from either compiler, even with
-Wall -Wextra -Wpedantic -Wconversion. When the arguments are variables,
swapping the distance and the minutes is reported only with
-Wconversion, because a double becomes an int, and this site’s
examples, like many projects, do not turn that warning on. (Clang
warns without it for a literal such as 2.5, which would lose its
fraction, but not for 3.0.) The fee is in dollars as a double, so
every caller that adds fees together rounds in its own way. And the
unit of each number, kilometres or metres, dollars or cents, is
something each reader has to remember.
The fix. Give each kind of value its own small type:
VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// A sum of money as a whole number of cents. Whole cents mean no rounding:// 10.05 dollars is exactly Cents{1'005}. std::int64_t is a 64-bit integer,// big enough for any realistic amount.// explicit, so that a caller has to name the type: a bare {2'500} would// otherwise turn into either one.struct Cents { explicit Cents(std::int64_t cents) : value(cents) {} std::int64_t value; // `= default` asks the compiler to write ==, comparing `value`, so a // test can check that two fees are equal. Declared as a friend inside // the struct, it is found whenever two Cents are compared. friend bool operator==(Cents, Cents) = default;};
// A distance as a whole number of metres. It is a different type from// Cents, even though both hold one integer, so one cannot be passed// where the other is expected.struct Metres { explicit Metres(std::int64_t metres) : value(metres) {} std::int64_t value;};
// The two priorities, by name. Unlike the flawed int, there is no third// value to pass by mistake.enum class Priority { normal, high };
// The same rules as the flawed version, with each input in its own type.// A swapped argument is now a compile error, because no parameter accepts// another parameter's type. std::chrono::minutes is the standard library's// type for a number of minutes. Returns the fee in cents. The 1'000 style// is a C++14 digit separator: the ' is ignored and only helps reading.inline Cents delivery_fee(Metres distance, std::chrono::minutes until_pickup, Priority priority, Cents basket) { // 3'000 cents is 30 dollars: free delivery, as before. if (basket.value >= 3'000) { return Cents{0}; } std::int64_t fee = 200; if (distance.value > 2'000) { // Integer division rounds down, so adding 999 first makes it round // up: one started km. For 2'001 m: (1 + 999) / 1'000 is 1; for // 3'000 m: (1'000 + 999) / 1'000 is still 1; for 3'001 m it is 2. const std::int64_t started_km = (distance.value - 2'000 + 999) / 1'000; fee += 50 * started_km; } if (priority == Priority::high) { fee += 150; } // Compares two durations; std::chrono::minutes{15} is fifteen minutes. if (until_pickup < std::chrono::minutes{15}) { fee += 100; } return Cents{fee};}Now a swapped call does not compile. Passing the minutes where the
distance goes gives, from GCC, “could not convert … from
‘std::chrono::minutes’ … to ‘primitive_obsession::fixed::Metres’”,
and from Clang, “no viable conversion from ‘std::chrono::minutes’ …
to ‘primitive_obsession::fixed::Metres’”. The constructors are
explicit for a reason. Without them, Cents and Metres are both
structures with one integer, so a caller who writes bare braces,
delivery_fee({2'500}, ..., {1'000}), gets either type from either
value, and a swap compiles again; both compilers accepted that call
before the constructors were added. With them, a caller has to write
the type’s name.
Money is a whole number of cents, so nothing is rounded. Time uses
std::chrono::minutes, which the standard library already provides;
there is no need to write a type for it. The page on
strong types and API contracts covers how
far to take this, including types that check their own range.
The test runs both versions over distances, times, priorities, and baskets on and around every edge in the rules, and requires the same fee in cents. All 168 combinations agree.
What the fix costs. Each type is a few lines, and callers have to
write Metres{2'500} instead of 2.5. For values that cross many
function boundaries, that cost is paid back the first time a swap is
caught. For a value used inside one function, a type adds reading and
catches nothing.
A related smell: data clumps. When the same three or four values
travel together into every function, such as distance, time to
pick-up, and priority, they are a missing type. A parameter object,
like Stay on the page on
incremental design evolution, gives
them a name and one place to add the next one.
Smell 2: feature envy
Section titled “Smell 2: feature envy”What it looks like. A function that is more interested in another object’s data than in its own. Here, two functions work out an order’s total by reaching into the order’s items:
VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// FLAWED (shown as a smell; do not copy). Order is bare data: it has no// functions, so the rule for its total has nowhere to live, and each// function that needs a total works it out for itself.struct Order { std::vector<Item> items; bool member = false; // members get 10% off};
// On the receipt. Adds price times quantity for each item, then takes// off a tenth for a member. total / 10 is integer division, so the// discount is rounded down: on 1'005 cents it is 100, and the member pays// 905.inline std::int64_t receipt_total(const Order& order) { std::int64_t total = 0; for (const Item& item : order.items) { total += item.price_cents * item.quantity; } if (order.member) { total -= total / 10; } return total;}
// On the checkout page, written later, by someone else. The same idea,// written differently, and here is where it goes wrong: total * 9 / 10// rounds the price down instead of the discount. On 1'005 cents that is// 9'045 / 10, which is 904, one cent less than the receipt. The two// agree only when the total is a whole multiple of ten cents.inline std::int64_t checkout_total(const Order& order) { std::int64_t total = 0; for (const Item& item : order.items) { total += item.quantity * item.price_cents; } return order.member ? total * 9 / 10 : total;}Why it hurts. The rule for an order’s total has no home, so each
function that needs it writes its own copy, and copies drift. The
receipt takes the discount off with total - total / 10, which rounds
the discount down. The checkout page, written later, works out
total * 9 / 10, which rounds the price down. They agree only when
the total is a whole multiple of ten cents; for every other member’s
order, the checkout page is one cent lower. The test shows one:
VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// LLD_TEST(name) defines one test, and LLD_CHECK_EQ(actual, expected)// records a failure, printing both values, if they are not equal. Both come// from the site's small test header, lld_test.hpp.//// Sets up one member's order whose total, 10.05, is not a multiple of ten// cents, and proves two things: the two flawed copies disagree by a cent,// and after the fix both screens give the receipt's answer.LLD_TEST(feature_envy_copies_drift_apart) { using feature_envy::Item; // Each inner {...} is one Item: name, price in cents, quantity. // 670 + 335 is 1'005 cents. const std::vector<Item> items{{"noodles", 670, 1}, {"dumplings", 335, 1}}; // 10.05 // The flawed Order is a plain struct, so braces fill its members in // order: a copy of items, then member = true. const feature_envy::flawed::Order old_order{items, true}; // The two envious copies round the member discount differently. // Receipt: 1'005 - 1'005 / 10 is 1'005 - 100, so 905. // Checkout: 1'005 * 9 / 10 is 9'045 / 10, so 904. LLD_CHECK_EQ(feature_envy::flawed::receipt_total(old_order), 905); LLD_CHECK_EQ(feature_envy::flawed::checkout_total(old_order), 904);
// The fixed Order calls its constructor, which copies the items (they // are const here, so they cannot be moved from). Both screens now // return order.total_cents(), so they must agree. const feature_envy::fixed::Order order{items, true}; LLD_CHECK_EQ(feature_envy::fixed::receipt_total(order), 905); LLD_CHECK_EQ(feature_envy::fixed::checkout_total(order), 905);}An order of 10.05 for a member is 9.05 on the receipt and 9.04 on the checkout page. That is the one-cent bug from the problem statement, and it is exactly the kind that comes from two copies of a rule: each copy looks right, and each passes a test with a round total such as 10.00.
The fix. Move the rule to the data it reads. The total becomes a
member of Order, and both functions ask for it:
VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// The total moved to the data it reads. Order is now a class whose items// and member flag are private, so outside code can no longer write its// own version of the total; it has to ask total_cents().class Order {public: // Takes the items by value and moves them into items_, so a caller // who passes a temporary vector pays for no copy. Order(std::vector<Item> items, bool member) : items_(std::move(items)), member_(member) {}
const std::vector<Item>& items() const { return items_; }
// The one place that knows how an order's total is worked out. The // discount is rounded down, as the receipt always did. std::int64_t total_cents() const { std::int64_t total = 0; for (const Item& item : items_) { total += item.price_cents * item.quantity; } // ?: picks the discounted total for a member, the full one // otherwise. total / 10 rounds the discount down, as before. return member_ ? total - total / 10 : total; }
private: std::vector<Item> items_; bool member_;};
// Both screens keep their old names, and now both ask the order, so// they cannot drift apart again.inline std::int64_t receipt_total(const Order& order) { return order.total_cents(); }inline std::int64_t checkout_total(const Order& order) { return order.total_cents(); }The fix had to choose one rounding, and it kept the receipt’s, because receipts are what customers were given. That choice is a behaviour change for the checkout page, and it is made on purpose and tested: the fixed version gives 9.05 in both places. A second test runs the fixed total against the old receipt over several baskets, with and without the discount, and requires them to agree.
When it is fine. Some functions read another object’s data because
they apply rules that belong somewhere else. Tax rules, for example,
belong to the tax module and change with the law, not with the order;
moving them into Order would make the order change for reasons that
have nothing to do with it. Ask which object’s rules the function
applies, not just whose data it reads. The page on
the single responsibility principle gives the
test: who asks for this code to change?
Smell 3: shotgun surgery
Section titled “Smell 3: shotgun surgery”What it looks like. One change, such as adding a payment method, needs small edits in many places. Here, what each payment method means is spread over four functions, which in the real app were in four files:
VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// FLAWED (shown as a smell; do not copy). Four questions about a payment// method, answered in four functions that lived in four files. Adding a// payment method means finding and editing all four, and nothing lists them.//// In checkout_page.cpp. The name shown to the customer.inline const char* label(Payment payment) { switch (payment) { case Payment::card: return "Card"; case Payment::cash: return "Cash on delivery"; case Payment::voucher: return "Voucher"; } // Reached only if `payment` holds a number that is not one of the // enum's names (possible with a cast). With no default: label, the // compiler (-Wswitch) warns if a new method has no case here. throw std::invalid_argument("unknown payment");}
// In pricing.cpp. The extra charge, in cents. Two case labels in a row// share one return: card and voucher both cost nothing extra.inline std::int64_t surcharge_cents(Payment payment) { switch (payment) { case Payment::cash: return 50; case Payment::card: case Payment::voucher: return 0; } throw std::invalid_argument("unknown payment");}
// In refunds.cpp. Where it goes wrong: there is no switch, so a new// method is silently refundable (it is not a voucher), and the compiler// has nothing to warn about.inline bool refundable(Payment payment) { return payment != Payment::voucher;}
// In courier_app.cpp. The same silent default: a new method means the// courier collects nothing, because it is not cash.inline bool courier_collects_money(Payment payment) { return payment == Payment::cash;}Why it hurts. The person adding a method has to know all four
places, and nothing tells them. The compiler helps only where there
is a switch. A scratch copy of the flawed code was given a fourth
method, wallet_app, and compiled with this site’s flags. Both
compilers reported the two switch statements, in label and
surcharge_cents, through -Wswitch, which -Wall turns on. The
other two functions compiled without a word: refundable says a
wallet payment can be refunded, because it is not a voucher, and
courier_collects_money says the courier collects nothing, because it
is not cash. Each might be right, by accident. That is how the
voucher bug in the problem statement shipped: when vouchers were
added, refundable did not exist yet, the refund screen allowed a
refund for every payment, and nothing pointed at it. The fix added
the fourth function, in a fourth file.
The fix. Gather everything the program knows about a payment method into one place:
VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// Everything the program knows about a payment method, in one place: one// member for each of the four old questions.struct PaymentRules { const char* label; std::int64_t surcharge_cents; bool refundable; bool courier_collects_money;};
// The one function to edit when a method is added. Each case returns all// four answers at once; {"Card", 0, true, false} fills the members in the// order they are declared: label, surcharge_cents, refundable,// courier_collects_money. A new enum value with no case is reported by// -Wswitch, and a case that gives only three answers is reported by// -Wmissing-field-initializers. Two bools given in the wrong order are not// caught, so each method still needs a test of its answers.inline PaymentRules rules_for(Payment payment) { switch (payment) { case Payment::card: return {"Card", 0, true, false}; case Payment::cash: return {"Cash on delivery", 50, true, true}; case Payment::voucher: return {"Voucher", 0, false, false}; } // As in the flawed version: only a value outside the enum gets here. throw std::invalid_argument("unknown payment");}The code that asked the four questions can now read the answers from
rules_for, and the test requires the fixed rules to match the four old functions for
every method. Adding wallet_app to the fixed version is one case.
Both compilers report the missing case through -Wswitch; and if the
new case returns only three of the four answers, both report the
missing member through -Wmissing-field-initializers, which -Wextra
turns on. Both checks were made on scratch copies.
A default: label in the switch would turn the first check off,
which is a good reason not to write one in a switch over an enum
that is meant to grow. GCC and Clang also have -Wswitch-enum, which
warns about a missing value even when there is a default:.
The second check has a limit. The compiler insists on four answers,
not on their order: a new case that returns {"Wallet app", 0, false, true}, with the two bool values swapped, compiles silently
with both compilers. That is the flag argument smell again, inside the
fix. C++20 designated initializers, {.label = "Wallet app", .surcharge_cents = 0, .refundable = true, .courier_collects_money = false}, name each answer, so a swap is visible in review. Neither
compiler accepts them in the wrong order with this site’s flags, but
for a member left out, GCC 11 warns and Clang 14 says nothing, so the
check above is weaker with them. Either way, each new method needs a
test of its four answers.
The opposite smell: divergent change. Shotgun surgery is one change touching many places. Divergent change is one place touched by many unrelated changes: a class edited for prices on Monday, for screen layout on Tuesday, and for the database on Wednesday. The two pull in opposite directions, and fixing one too hard creates the other. Gather what changes together; separate what changes for different reasons. If, later, payment methods differ in behaviour and not just in a few values, the table becomes a set of objects behind an interface, which is the Strategy pattern. Until then, a table is simpler.
Smell 4: flag arguments
Section titled “Smell 4: flag arguments”What it looks like. A function takes a bool that selects what it
does, and the call site says true or false:
VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// FLAWED (shown as a smell; do not copy). Builds the message sent to a// customer about their order. Two bools choose what it does: `late` picks// the apology or the greeting, and `sms` adds the opt-out line that text// messages need. Two flags make four behaviours, and every one needs a test.inline std::string notification_text(const std::string& customer, bool late, bool sms) { // ?: chooses one of the two sentences. "Sorry, " + customer works // because customer is a std::string, so + joins strings. std::string text = late ? "Sorry, " + customer + ": your order is running late." : "Hello " + customer + ": your order is on its way."; if (sms) { text += " Reply STOP to opt out."; } return text;}
// At a call site:// send(notification_text(customer, false, true));// Where it goes wrong: a reader cannot tell what false and true mean// without opening the function, and swapping them still compiles, because// both parameters are bool. This call means "on time, by SMS".Why it hurts. notification_text(customer, false, true) cannot be
read without opening the function. Two bool parameters can be
swapped, and the call still compiles. And a function with two flags
has four behaviours, each of which needs a test.
The fix. Name the choice with an enum class, or, if the branches
share little, write two functions:
VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// Each choice gets its own enum class, with a name for each option. The// two are different types, so a Channel cannot be passed where a Progress// goes: swapping the arguments is now a compile error.enum class Progress { on_time, late };enum class Channel { email, sms };
// The same text as the flawed version for each of the four combinations;// only the way the caller says what they want has changed.inline std::string notification_text(const std::string& customer, Progress progress, Channel channel) { std::string text = progress == Progress::late ? "Sorry, " + customer + ": your order is running late." : "Hello " + customer + ": your order is on its way."; if (channel == Channel::sms) { text += " Reply STOP to opt out."; } return text;}
// At a call site:// send(notification_text(customer, Progress::on_time, Channel::sms));// The call now reads as a sentence, with no need to open the function.The call now says what it means, and passing the two values in the wrong order is a compile error with both compilers, which was checked on a scratch file. The test requires the same text from both versions for all four combinations.
When it is fine. A bool that is genuinely a value, set from data,
is not a flag argument: set_visible(checkbox.checked()) is clear,
and an enum would add nothing. The smell is a literal true or
false at a call site that a reader cannot decode.
Smell 5: message chains
Section titled “Smell 5: message chains”What it looks like. Code that reaches through one object to get another, and through that to a third:
VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// FLAWED (shown as a smell; do not copy). Three plain structs, each holding// the next by value: a Customer has an Account, which has a Wallet, which// has a balance. Everything is public, so any code can reach all the way in.struct Wallet { std::int64_t balance_cents = 0;};struct Account { Wallet wallet;};struct Customer { Account account;};
// Checkout knows how a customer's money is stored, three levels down.// Where it goes wrong: the chain customer.account.wallet.balance_cents// spells out the whole layout. If an account gets a second wallet or a// credit limit, this line, and every line like it, has to change.inline bool can_place_order(const Customer& customer, std::int64_t total_cents) { return customer.account.wallet.balance_cents >= total_cents;}Why it hurts. Checkout now depends on how a customer’s money is stored, three levels down. If the app adds a second wallet, or a credit limit on the account, every chain like this one has to change, and they are spread across the code. The page on the Law of Demeter explains the rule behind this: talk to the objects you were given, not to objects that they hold.
The fix. Ask the question you have, and let each object answer it from what it holds:
VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// Each level now keeps its data private and answers a question about it.// Nobody outside a Wallet can read balance_cents_; they can only ask// whether it covers an amount.class Wallet {public: explicit Wallet(std::int64_t balance_cents) : balance_cents_(balance_cents) {} bool covers(std::int64_t cents) const { return balance_cents_ >= cents; }
private: std::int64_t balance_cents_;};
// An Account answers "can you pay this?" by asking its wallet. Today// that is a plain forward; a credit limit would be added here, and only// here. The constructor copies the Wallet it is given, which is cheap:// a Wallet is one integer.class Account {public: explicit Account(Wallet wallet) : wallet_(wallet) {} bool can_pay(std::int64_t cents) const { return wallet_.covers(cents); }
private: Wallet wallet_;};
// A Customer answers the same question by asking its account. Checkout// talks only to the customer it was given.class Customer {public: explicit Customer(Account account) : account_(account) {} bool can_pay(std::int64_t cents) const { return account_.can_pay(cents); }
private: Account account_;};
// Checkout asks the question it has, and no more.inline bool can_place_order(const Customer& customer, std::int64_t total_cents) { return customer.can_pay(total_cents);}Now a credit limit is a change to Account::can_pay alone. The test
requires the same answer from both versions for a balance below, at,
and above the total.
The overcorrection: a middle man. The fix adds two forwarding
functions. That is fine when each level adds meaning: an account that
later checks a credit limit is more than a wrapper. But a class whose
methods all just forward to another object is a smell of its own,
called a middle man, and it costs a layer of reading for nothing. If
Account ends up with twenty methods that each call the wallet, the
account is the wrong abstraction, and the callers should be given
the wallet.
When it is fine. A chain through plain data, such as
config.delivery.fees.base in a settings structure, has no behaviour
to hide, so there is nothing to ask. A chain that returns the same
kind of thing each time, such as a builder or a ranges pipeline, is a
fluent interface, not a message chain.
Smell 6: temporal coupling
Section titled “Smell 6: temporal coupling”What it looks like. An object that must have its methods called in a particular order, where the order is enforced by a comment:
VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// FLAWED (shown as a smell; do not copy). A courier is built with only a// name, and the vehicle is given later. Between the two calls the object// exists in a state that means nothing, and only a comment says so.class Courier {public: explicit Courier(std::string name) : name_(std::move(name)) {}
// Must be called before can_take. Nothing but this comment says so: // the compiler accepts can_take on a courier that never had this call. void set_vehicle(Vehicle vehicle) { vehicle_ = vehicle; has_vehicle_ = true; }
// True if the distance is within the vehicle's range. Throws // std::logic_error if set_vehicle was never called: the order mistake // is found only when the program runs, not when it compiles. bool can_take(int distance_metres) const { if (!has_vehicle_) { throw std::logic_error(name_ + " has no vehicle yet"); } return distance_metres <= range_metres(vehicle_); }
private: std::string name_; Vehicle vehicle_ = Vehicle::bicycle; // meaningless until set_vehicle // A second member whose only job is to say whether the first one is // real. Every method that uses vehicle_ has to check it first. bool has_vehicle_ = false;};Why it hurts. Between construction and set_vehicle, the courier
is in a state with no meaning: vehicle_ holds a value that nobody
chose. Every method has to check for that state, and every caller has
to remember the order. The new screen in the problem statement forgot.
The test shows what happens:
VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// LLD_CHECK_THROWS(expression, type) fails the test unless the expression// throws an exception of that type.//// Proves two things. First, the flawed courier throws if it is asked// before it has a vehicle: the wrong order is caught only at run time.// Second, once both couriers have a scooter (range 12'000 m), they give// the same answer at 0, exactly at the range, and one metre past it.LLD_TEST(temporal_coupling_the_old_courier_fails_if_used_too_soon) { using namespace temporal_coupling; flawed::Courier old_courier("Sam"); LLD_CHECK_THROWS(old_courier.can_take(1'000), std::logic_error); // The step the new screen forgot. From here on, can_take works. old_courier.set_vehicle(Vehicle::scooter);
// The fixed courier gets its vehicle in the constructor: no second step // to forget. const fixed::Courier courier("Sam", Vehicle::scooter); for (const int metres : {0, 12'000, 12'001}) { LLD_CHECK_EQ(courier.can_take(metres), old_courier.can_take(metres)); }}The fix. Make the meaningless state impossible to build. The constructor takes everything a courier needs to be valid:
VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// A courier cannot be built without a vehicle: the only constructor asks// for one, so Courier courier("Sam"); does not compile. There is no// "no vehicle yet" state, so there is no flag and no check.class Courier {public: // The name is taken by value and moved into name_, so a temporary // string is not copied. Courier(std::string name, Vehicle vehicle) : name_(std::move(name)), vehicle_(vehicle) {}
// A courier changes vehicle; it is never without one. void change_vehicle(Vehicle vehicle) { vehicle_ = vehicle; }
// Always has a vehicle to look at, so it never throws for a missing one. bool can_take(int distance_metres) const { return distance_metres <= range_metres(vehicle_); }
private: std::string name_; Vehicle vehicle_;};Now fixed::Courier courier("Sam"); does not compile, with either
compiler, which was checked on a scratch file; a courier always has a
vehicle, so can_take has nothing to check. Changing vehicle is
still possible, but it replaces one valid value with another. This is
the invariant idea from the
page on constructors and lifetime:
the constructor establishes it, and every method keeps it.
When the order is real. Some steps genuinely come in order: open a file, write it, close it. C++ handles the most common case with RAII: the constructor opens, the destructor closes, and there is no state in between to misuse. For longer sequences, each step can return a different type, so that the next step is only available once the previous one is done. A comment that says “call this first” is the weakest of the three.
The god class
Section titled “The god class”A god class is a class that knows and does too much: orders, couriers,
payments, and notifications, all in one DeliveryApp, with a test
that has to build everything to check anything. Its declaration
usually gives it away. This one was compiled with both compilers,
together with declarations of the types it names:
// FLAWED (shown as a smell; do not copy). Declarations only: one class for// orders, couriers, payments, and notifications. Each group of member// functions below touches a different part of the private data.class DeliveryApp {public: // Takes the gateway and the email client by reference: the app uses // objects that someone else owns, and they must outlive the app. DeliveryApp(PaymentGateway& gateway, EmailClient& email); OrderId place_order(CustomerId customer, std::vector<Item> items); void assign_courier(OrderId order); bool take_payment(OrderId order, Payment method); void notify(OrderId order, Progress progress); std::int64_t weekly_pay_cents(CourierId courier) const; // ... and forty more
private: // Each std::map looks up one value by its key: an order by its id, // a courier by theirs. std::map<OrderId, Order> orders_; std::map<CourierId, Courier> couriers_; PaymentGateway& gateway_; // used, not owned EmailClient& email_; // used, not owned int overtime_after_hours_ = 40;};Each member function uses a different part of the data:
place_order uses orders_, assign_courier and weekly_pay_cents
use couriers_, take_payment uses gateway_, and notify uses
email_. Every change touches the class, so every change conflicts with every other. The page on
finding classes
shows how to spot one while designing, and the fix is usually to
split it along the data that each group of methods uses: methods that
read the same few members belong together, as the page on
cohesion and coupling explains.
Here the split gives an order book, a dispatcher, a payment
service, and a notifier, each with its own data and its own tests,
and a short function that runs a checkout by calling them in turn.
A god class is not one smell but where several end up: methods move
to where the data is, so a class that holds too much data attracts
too many methods, and divergent change is the sign that it has.
Smells covered elsewhere
Section titled “Smells covered elsewhere”| Smell | What to look for | Where it is covered |
|---|---|---|
| Speculative generality | An interface with one implementation and no test double; options that nobody sets | The cost of abstraction |
| Pattern soup | Factories, managers, and strategies with one choice each | When patterns hurt |
| Global and shared state | Singletons and statics that any code can change | What shared and global state cost |
| The wrong abstraction | A shared function full of flags for each caller’s special case | DRY, KISS, and YAGNI |
| Unclear ownership | std::shared_ptr everywhere, owning raw pointers, cycles |
Ownership graphs and smart pointers |
| Hidden inputs | A function that reads the clock or a global, so it is hard to test | Safe refactoring of legacy code |
Removing a smell safely
Section titled “Removing a smell safely”Every fix on this page is a refactoring, so the rules from Safe refactoring of legacy code apply:
- Get a test first. The tests in this example compare the old and new versions on the same inputs. In real code the old version is the commit before the change, and the test is written before the change, against the old code.
- One smell at a time. Each fix above is a separate step with its own check. Fixing primitive obsession and feature envy in one change makes a failing test impossible to explain.
- Decide behaviour changes on purpose. The feature envy fix changed the checkout page’s price for some orders, by one cent. That was the point, but it is a change of behaviour, not a refactoring, so it is named, tested, and told to the people who own the page.
- Let the compiler help. Four of the six fixes turn a silent mistake into something the compiler reports: three into errors, and the shotgun surgery fix into warnings, which this site’s builds treat as errors. That is the strongest kind of check, because it runs on every build, including code written later by someone who never read this page.
Design debt
Section titled “Design debt”The metaphor. The idea of design debt, often called technical debt, is widely attributed to Ward Cunningham. A design shortcut is like a loan: you get something now, usually time, and you pay for it later. The principal is what it would cost to fix the design. The interest is the extra effort that every change pays while the design stays as it is: the four files to edit for each payment method, the second rounding to check, the order of calls to remember.
The metaphor is useful because it separates two questions that people mix up. “Is this code bad?” is a matter of taste. “How much does this code cost us each month?” can be estimated, and it decides what to fix.
Kinds of debt. A common way to sort debt, widely associated with Martin Fowler, asks two questions. Was it taken on deliberately, or did you only notice later? And was the decision prudent, or reckless?
- Deliberate and prudent: “we ship with the old signature
deprecated, and remove it when the last caller has moved.” The
deprecated
parking_feeon the page on incremental design evolution is this kind: known, written down, with a plan. - Accidental and prudent: “now that we have built it, we see what the design should have been.” This is normal and healthy: some designs can only be learned by building them. The shotgun surgery above is this kind: with only card and cash, a few small functions were enough, and vouchers showed that each method’s rules belonged together.
- Reckless, deliberate or not: copy-paste because there was no time, a skipped test, a global added to get a demo working. It is the expensive kind, because nobody weighed what it would cost, and it is often not recorded either.
Not every mess is debt. Code that works and never changes charges no interest. A tangled module that nobody has edited in two years may be ugly, but fixing it costs effort now, adds risk, and saves nothing.
A debt register
Section titled “A debt register”Debt that nobody writes down is not managed, only forgotten. A short list, kept next to the code or in the issue tracker, is enough. For the delivery app it might look like this:
| Debt | Interest: what it costs each time | How often | Plan |
|---|---|---|---|
| Payment rules spread over four files | Four edits per new method, two of which the compiler cannot find | A new method about every quarter | Gather into one table before the wallet app is added |
| Order total worked out in two places | A rounding difference has already shipped; every price change is two edits | Every pricing change | Move the total into Order; done, with a test |
Courier needs set_vehicle before use |
Each new screen must know the order; one crashed | Rare: a new screen a year | Fix the next time dispatch code is changed |
| Old notification code with two flags | Each review of it is slow; four behaviours to test | It changes about once a year | Leave it; fix if a third flag is ever needed |
The last row is a decision not to pay, which is a legitimate entry. The register makes it a decision instead of an accident.
Deciding what to pay first
Section titled “Deciding what to pay first”Interest is paid per change, so the debt that matters is in code that changes often. A rough priority is the cost per change times how often the code changes. The version control history shows the second number: the files that change most often, and the files that always change together, are where debt charges the most. A file that has been edited forty times this year, in many of the same commits as three others, is a stronger candidate than one with a worse smell and no edits.
Paying it down
Section titled “Paying it down”- On the way to a feature. The cheapest moment to fix a design is when the next change has to pass through it anyway: refactor first, so the feature becomes easy, then add the feature. That is the preparing refactoring from incremental design evolution, and it ties each repayment to a change someone asked for.
- In small steps, always tested. A smell fixed in a separate, reviewable change, with a test that shows nothing else changed, is low risk. A month-long clean-up branch that touches everything is high risk and hard to review.
- Not without a net. Code without tests is the worst place to pay debt in big pieces. Put a net under it first: a characterization test or a golden master, as on the page on safe refactoring of legacy code.
When not to pay
Section titled “When not to pay”- The code is about to be deleted or replaced.
- The code rarely changes, so the interest is close to zero.
- The fix is riskier than the interest, for example in code with no tests that is about to ship.
- The “fix” is a pattern or an abstraction for a future that has not arrived. That is not paying debt; it is borrowing in a different currency.
Common mistakes
Section titled “Common mistakes”- Treating every smell as a bug. A smell is a reason to look, and the three questions decide. Refactoring code that nobody changes costs effort and risk and saves nothing.
- Fixing a smell without a test. Every fix above changed structure in ways that could break behaviour. Without a comparison, a one-cent rounding change looks like any other diff.
- Overcorrecting. Message chains fixed with forwarding methods on every class become a middle man; shotgun surgery fixed by gathering everything into one class becomes a god class; primitive obsession fixed with a type for every local variable becomes noise.
- Smuggling in a behaviour change. The feature envy fix changed a price. That is fine if it is said, tested, and agreed; it is a bug if it is hidden in a refactoring.
- Fixing debt in one big rewrite. A rewrite loses the rules nobody wrote down, and it ships nothing until it is finished. Small repayments on the way to features are safer and visible.
- Keeping debt in people’s heads. “We all know about that” stops being true when people leave. Write it down, with the interest and the plan.
When the requirements change
Section titled “When the requirements change”The app adds a fourth payment method, a wallet app. In the wallet app, money moves before the order is accepted, so it can be refunded, and the courier collects nothing.
- In the flawed version, the developer has to find four functions
in four files. The compiler names two of them; the other two compile
unchanged and give answers that, this time, happen to be right. If
the wallet app could not be refunded,
refundablewould still say it could, and no test or warning would say otherwise until a customer asked for a refund. - In the fixed version, the change is one
caseinrules_for, with four answers. The compiler insists that there are four, though not on their order. The comparison with the old functions still covers the three old methods, and the new method’s four answers get a test of their own, worked out by hand.
The second version is cheaper for this change. It would be more expensive if payment methods were never added, because there would be a table to read instead of four short functions. That is the third question again: what the fix costs depends on the changes you actually make.
Exercise
Section titled “Exercise”Exercise: Name the smell
Each snippet below is from the same delivery app. Every snippet was compiled with GCC 11.4 and Clang 14, with this site’s warning flags, as a file of its own with the declarations it needs. For each one, name the smell, or say that there is none; say what change or mistake it makes likely; and say what you would do.
1. In the checkout code:
void send_receipt(const Order& order, bool include_tax, bool as_pdf, bool copy_restaurant);
void checkout(const Order& order) { send_receipt(order, true, false, true);}2. In the payroll module:
class Payroll {public: std::int64_t weekly_pay_cents(const Courier& courier) const { // Basic pay: every hour at the courier's rate. std::int64_t pay = courier.hourly_rate_cents() * courier.hours_this_week(); // Hours beyond the limit are already paid once above; adding half // the rate again makes each of them time and a half. if (courier.hours_this_week() > overtime_after_hours_) { const int extra = courier.hours_this_week() - overtime_after_hours_; pay += courier.hourly_rate_cents() * extra / 2; // time and a half } return pay + courier.tips_cents(); }
private: int overtime_after_hours_ = 40;};3. In the dispatch code:
class RouteBuilder {public: void start_at(Location depot); void add_stop(Location stop); Route build() const; // throws std::logic_error if start_at was not called};4. No code this time. Adding a “grocery” kind of store meant
editing a switch in search.cpp, opening_hours.cpp,
delivery_fee.cpp, and tax.cpp, and a lookup table of icons in the
app. The icon was missed and found by a customer.
5. In the order service:
void refund(int order_id, int customer_id, int amount_cents);
void cancel(const Customer& customer, const Order& order) { refund(customer.id, order.id, 1'250); // compiles; the ids are swapped}6. Made by the order service for the screen that lists past orders:
struct OrderSummary { std::string restaurant; int item_count; std::int64_t total_cents;};Show the explained answer
-
Flag arguments. Three
boolparameters give eight behaviours, andtrue, false, truecannot be read at the call site; any two can be swapped without a compile error. Replace them with enums that say what each choice is. If there are several options and most callers keep the defaults, a small options structure, set by name with designated initializers, reads well too:send_receipt(order, {.include_tax = true, .copy_restaurant = true}). -
It looks like feature envy, but probably is not. The function calls the courier six times, for three of its values, and uses one value of its own. But the rule it applies, overtime after 40 hours at time and a half, is a payroll rule: it changes with contracts and the law, not with couriers. Moving it into
Courierwould make the courier change for payroll reasons. Leave it where it is. If the courier’s hours and rate are read in many places, a smallTimesheetvalue that payroll receives is a better step than moving the rule. This is why the question is whose rules a function applies, not whose data it reads. -
Temporal coupling. A builder that has not been given a depot is in a state with no meaning, and
buildhas to check for it. Make the depot a constructor argument, so the state cannot be built. This answer was compiled with both compilers:class RouteBuilder {public:// stops_{depot} starts the list with one stop, the depot, so a// builder can never exist without one.explicit RouteBuilder(Location depot) : stops_{depot} {}void add_stop(Location stop) { stops_.push_back(stop); }Route build() const { return Route{stops_}; }private:std::vector<Location> stops_; // never empty: the depot is first};buildno longer throws, because there is nothing left to check. -
Shotgun surgery. What a kind of store means is spread over five places, and the one that was missed was the one the compiler cannot see: a table, not a
switch. Gather the values that are about the kind of store, such as its icon, its search category, and its delivery fee, into one place, asrules_fordoes for payment methods; leave rules that change for other reasons, such as tax, in their own modules. The icon table can also be checked by the compiler: aswitchwithoutdefault:, or astd::arraywith one entry per value and astatic_asserton its size. If kinds of store come to differ in behaviour, not just in values, the Strategy pattern is the next step; not before. -
Primitive obsession. Two identifiers of the same type can be swapped silently, and the comment admits that they were. Give each identifier and the money their own types. With
struct OrderId { int value; };, a matchingCustomerId, and aCents, the swapped call is a compile error. That was checked with both compilers: GCC reports that it “could not convert ‘customer.Customer::id’ from ‘const CustomerId’ to ‘OrderId’”, and Clang reports “no matching function for call to ‘refund’”. -
No smell. A plain structure with public members is the right tool for data that only travels: it has no invariant to protect and no rules that live elsewhere and get copied. It would be a smell if screens started working out totals from it, or if code elsewhere kept checking that
item_countwas not negative. If the app has aCentstype, using it fortotal_centswould be a small improvement, not a fix. One real problem:item_countandtotal_centshave no initial values, soOrderSummary summary;leaves them indeterminate, and reading them is undefined behaviour. Give them= 0.
More smells to identify, with longer code, are planned for the practice section, in Identify the design smell.
Summary
Section titled “Summary”- A design smell is a visible sign that a design may be making change harder. It is a reason to look, not proof. Ask what change it makes harder, how often that change happens, and what the fix costs.
- Primitive obsession lets callers swap values the compiler cannot tell apart; small types make the swap a compile error.
- Feature envy leaves a rule without a home, so it gets copied, and copies drift: here, by one cent.
- Shotgun surgery spreads one concept over many places, and the compiler finds only some of them; gather it into one place.
- Flag arguments make call sites unreadable; name the choice.
- Message chains tie callers to the structure of objects they should not know; ask the question instead, but do not turn every class into a forwarder.
- Temporal coupling leaves objects in states with no meaning; make such states impossible to build.
- Every fix is a refactoring, so it needs a test, and any change of behaviour it brings must be on purpose.
- Design debt is a shortcut, or a design that no longer fits, that makes each later change cost more: fixing it is the principal, and the extra cost of each change is the interest. Write it down, weigh it by how often the code changes, pay it on the way to features in small tested steps, and decide openly when not to pay.