Skip to content

DRY, KISS, and YAGNI

Difficulty: Beginner

Key concepts

  • DRY
  • duplicated knowledge
  • coincidental similarity
  • wrong abstraction
  • KISS
  • YAGNI
  • rule of three
  • What DRY really asks for: one home for each piece of knowledge, not the removal of every pair of similar lines.
  • How to tell duplicated knowledge from coincidental similarity, and why merging the second kind creates a wrong abstraction.
  • What KISS and YAGNI mean in design, and what they do not excuse.
  • How the three rules pull against each other, and how to decide.
Rule Stands for What it asks What it does not mean
DRY Don’t Repeat Yourself Each fact or rule the program knows has one home. “Merge any two functions that look alike.”
KISS Keep It Simple Choose the simplest design that meets the real requirements. “Write the shortest code,” or “skip tests and error handling.”
YAGNI You Aren’t Gonna Need It Do not build features or extension points that nobody has asked for. “Do not think ahead,” or “write code that is hard to change later.”

(KISS is often expanded with a less polite last word. The idea is the same.)

A bookshop with a café sells books and drinks. The discounts:

  1. FR-1 Members get 10% off everything.
  2. FR-2 Students get 10% off books only.
  3. FR-3 Staff get 25% off everything, but at most 5.00 off one item. (Staff discount was 10% too, until last year.)
  4. FR-4 The till shows the price, and the printed receipt shows the normal price and the price paid. They must agree.

A customer complains: the till charged 18.00 for a novel, but the receipt says 17.99.

DRY is not about text. It is about knowledge: a business rule, a format, a constant, a decision. If the same knowledge is written in two places, a change to it must be made in both, and one day someone will change only one.

Here is how the till and the receipt work out the member price:

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

before.hpp
// Before, problem 1: the same rule written twice. The till and the receipt
// were written by different people, and each works out the member price.
namespace before {
// `inline` lets a function be defined in a header that several files
// include. All prices are whole cents in an int: 1999 means 19.99.
// The till's version of "10% off". cents / 10 is integer division, which
// throws away any remainder, so it rounds the DISCOUNT down: for 1999
// cents the discount is 199 (not 199.9), and the price is 1800, or 18.00.
inline int till_member_price(int cents) { return cents - cents / 10; }
// The receipt's version, for the line "novel 19.99 -> 17.99".
inline std::string receipt_member_line(const Item& item) {
// Multiplying first, then dividing, rounds the PRICE down instead:
// 1999 * 90 is 179910, and 179910 / 100 is 1799 (the .1 is dropped).
// So the receipt says 17.99 while the till charges 18.00.
const int member_cents = item.price_cents * 90 / 100; // also "10% off"
// euros (from shop.hpp) turns cents into text: 1999 becomes "19.99".
return item.name + " " + euros(item.price_cents) + " -> " + euros(member_cents);
}

Both lines mean “10% off”. They are not even the same text, which is why nobody noticed they were duplicates. cents - cents / 10 rounds the discount down (1999 cents gives 199 off, so 18.00), and cents * 90 / 100 rounds the price down (17.99). Same rule, two roundings, a one-cent argument at the counter.

This is the dangerous kind of duplication: duplicated knowledge. The fix is to give the rule one home and make both callers ask it. Before writing that home, someone must decide which rounding is right. That is a business question, not a coding one. The shop chose to round the discount to the nearest cent.

  • Two places would have to change together, for the same reason, when a person asks for one change.
  • A bug report says two parts of the program disagree.
  • A constant like 40 * 60, 0.1, or "%Y-%m-%d" appears in several files, each time meaning the same business fact.
  • The same validation (“member IDs have 8 digits”) is checked in the UI, the parser, and the database layer, in slightly different ways. (Some of that can be acceptable across a team boundary; see “DRY across boundaries” below.)

The wrong abstraction: when similar code is not the same knowledge

Section titled “The wrong abstraction: when similar code is not the same knowledge”

Now the other direction. A few years ago, all three discounts were “10% off”, so someone merged them into one function. Then the staff discount changed, and later the student discount was limited to books. Each change added a parameter:

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

before.hpp
// Before, problem 2: once, every discount was "10% off", so they were merged
// into one function. Each later change added a parameter to it.
// cap_cents < 0 means "no cap".
// Returns the discount in cents (not the price). Each parameter was added
// for one rule: books_only for students, cap_cents for staff, percent for
// whichever rule changed its number. The customer is only used to say
// "regular customers get nothing"; the real differences between the rules
// are in the arguments each caller passes.
inline int discount_cents(const Item& item, Customer customer, bool books_only, int percent,
int cap_cents) {
if (customer == Customer::regular) return 0;
if (books_only && item.category != Category::book) return 0; // the student rule
int off = item.price_cents * percent / 100; // rounds the discount down
if (cap_cents >= 0 && off > cap_cents) off = cap_cents; // the staff rule's cap
return off;
}
// Chooses the rule for each kind of customer, by passing a different mix
// of flags to the shared function. To understand the student rule, a
// reader must decode `true, 10, -1`: books only, 10%, and -1 for "no cap".
inline int price_for(const Item& item, Customer customer) {
switch (customer) {
case Customer::regular: return item.price_cents;
case Customer::member: return item.price_cents - discount_cents(item, customer, false, 10, -1);
case Customer::student: return item.price_cents - discount_cents(item, customer, true, 10, -1);
case Customer::staff: return item.price_cents - discount_cents(item, customer, false, 25, 500);
}
return item.price_cents;
}
} // namespace before

It works; the tests show it gives the right prices. But look at what it has become:

  • Five parameters: one bool flag and one sentinel value (-1 meaning “no cap”). Each call site passes its own mix, such as false, 10, -1, true, 10, -1, or false, 25, 500, which a reader must decode. The customer parameter is only checked against regular; the real rules are in the flags at the call sites.
  • The function belongs to nobody. Membership is a marketing decision, student pricing is a partnership with a university, and the staff discount is an HR benefit. Three owners share one function, so each change risks the other two.
  • Every new rule makes it worse. “Members get 15% off books” can be squeezed in by passing item.category == Category::book ? 15 : 10 as the percentage, but then the member rule lives half in the call site and half in the shared function. “Members get a flat 1.00 off” cannot be squeezed in at all: it needs a new mode parameter that every caller must pass.

This is a wrong abstraction: code that was merged because it looked alike, when the things it expressed were different rules that happened to match for a while. That was coincidental similarity. A wrong abstraction is often worse than the duplication it removed, because it couples rules that should change separately.

The way out is to undo the merge: copy the shared code back into each caller, delete the flags each one does not need, and then look again for the knowledge that really is shared.

There is one piece of knowledge that is shared by all three discounts: how a percentage turns into cents, with the shop’s chosen rounding. That gets one home. The three rules get one each:

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

pricing.hpp
// One piece of shared knowledge: how a percentage becomes cents. The shop
// decided to round the discount to the nearest cent (half a cent rounds up).
// Assumes 0 <= percent <= 100, and 0 <= cents well under 20 million, so
// cents * percent fits in an int.
// How the rounding works: cents * percent is the discount in hundredths
// of a cent. Adding 50 (half of 100) before the integer division, which
// drops the remainder, rounds to the nearest cent instead of always down.
// For 1999 cents at 10%: 19990 + 50 = 20040, and 20040 / 100 = 200.
// constexpr: it can also be worked out while compiling.
constexpr int percent_of(int cents, int percent) { return (cents * percent + 50) / 100; }
// Three business rules. They looked alike once; each has its own owner and
// its own reasons to change, so each has its own function.
[[nodiscard]] int member_price(const Item& item); // 10% off everything
[[nodiscard]] int student_price(const Item& item); // 10% off books only
[[nodiscard]] int staff_price(const Item& item); // 25% off, at most 5.00 per item
// Each returns the price to pay, in cents. [[nodiscard]] asks the compiler
// to warn if a caller ignores it: working out a price and then dropping
// it would always be a mistake.
// The one place that knows which rule applies to which customer.
[[nodiscard]] int price_for(const Item& item, Customer customer);
// The till and the receipt both ask price_for; neither has a rule of its own.
[[nodiscard]] int till_price(const Item& item, Customer customer);
[[nodiscard]] std::string receipt_line(const Item& item, Customer customer);

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

pricing.cpp
// Each rule is the price minus its discount, and every discount is worked
// out by percent_of, so all three round the same way.
// Members: 10% off everything. 1999 cents: 1999 - 200 = 1799.
int member_price(const Item& item) { return item.price_cents - percent_of(item.price_cents, 10); }
// Students: 10% off books; anything else (the cafe) is full price.
int student_price(const Item& item) {
if (item.category != Category::book) return item.price_cents; // no discount
return item.price_cents - percent_of(item.price_cents, 10);
}
// Staff: 25% off, but never more than 5.00 off one item. std::min picks
// the smaller of the two: the 25% discount, or the 500-cent cap. For the
// 4500-cent atlas, 25% is 1125, so the cap wins and the price is 4000.
int staff_price(const Item& item) {
constexpr int max_off_cents = 500;
return item.price_cents - std::min(percent_of(item.price_cents, 25), max_off_cents);
}
// Picks one rule per customer. There is a case for every Customer value
// and no `default:`, so if a new kind of customer is added, GCC and Clang
// warn (with -Wall) that this switch does not handle it.
int price_for(const Item& item, Customer customer) {
switch (customer) {
case Customer::regular: return item.price_cents;
case Customer::member: return member_price(item);
case Customer::student: return student_price(item);
case Customer::staff: return staff_price(item);
}
return item.price_cents; // not reached for valid enum values
}

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

pricing.cpp
// Both ask price_for, so they cannot disagree: a change to a rule reaches
// the till and the receipt together.
int till_price(const Item& item, Customer customer) { return price_for(item, customer); }
// "novel 19.99 -> 17.99": the name, the full price, and the price to pay.
std::string receipt_line(const Item& item, Customer customer) {
return item.name + " " + euros(item.price_cents) + " -> " + euros(price_for(item, customer));
}

Look at what was merged and what was not:

Code Shared? Why
rounding a percentage (percent_of) yes, one function one decision, made once by the shop; if it changes, it changes for every discount
member, student, and staff rules no, three functions three owners, three reasons to change; the lines price - percent_of(price, 10) look alike, but mean different things
choosing a rule for a customer (price_for) yes, one function the till and receipt must agree, so there is one place that answers “what does this customer pay?”
till and receipt no, two functions they show the price in different ways; neither has a rule of its own (till_price is a one-line call to price_for, kept so the till’s code reads as the till’s)

member_price and student_price both contain item.price_cents - percent_of(item.price_cents, 10). That is not a DRY violation. If the membership scheme changes, the student line must stay as it is. Similar text, different knowledge.

The switch in price_for covers every value of Customer. GCC and Clang warn (with -Wall) when a switch over an enum misses a value, so adding a new kind of customer without a rule is reported when the code is compiled. Two caveats: it is a warning, not an error, unless the build uses -Werror; and a default: label silences it, so do not add one. The return item.price_cents; after the switch gives no discount if an out-of-range value ever reaches it.

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

main.cpp
// Three items, each written as {name, price in cents, category}.
const std::vector<Item> items{
{"novel", 1999, Category::book},
{"atlas", 4500, Category::book},
{"coffee", 350, Category::cafe},
};
// std::setw(5) pads the next value to 5 characters, so the columns
// line up: " 3.15" under "18.00".
std::cout << "-- before: member price at the till and on the receipt --\n";
for (const Item& item : items) {
std::cout << " till " << std::setw(5) << euros(before::till_member_price(item.price_cents))
<< " receipt " << before::receipt_member_line(item) << '\n';
}
std::cout << "-- after: one rule, asked by both --\n";
for (const Item& item : items) {
std::cout << " till " << std::setw(5) << euros(till_price(item, Customer::member))
<< " receipt " << receipt_line(item, Customer::member) << '\n';
}
// A small fixed table: each entry pairs a label to print with the
// Customer value it stands for. `const auto& [label, customer]` then
// unpacks each pair into two names (a structured binding).
std::cout << "-- after: every customer --\n";
const std::pair<const char*, Customer> customers[]{{"regular", Customer::regular},
{"member", Customer::member},
{"student", Customer::student},
{"staff", Customer::staff}};
for (const auto& [label, customer] : customers) {
// std::left pads the label on the right (left-aligned); std::right
// switches back, so the prices that follow are right-aligned.
std::cout << " " << std::left << std::setw(8) << label << std::right;
for (const Item& item : items) std::cout << ' ' << std::setw(6) << euros(price_for(item, customer));
std::cout << '\n';
}
Expected output
-- before: member price at the till and on the receipt --
till 18.00 receipt novel 19.99 -> 17.99
till 40.50 receipt atlas 45.00 -> 40.50
till 3.15 receipt coffee 3.50 -> 3.15
-- after: one rule, asked by both --
till 17.99 receipt novel 19.99 -> 17.99
till 40.50 receipt atlas 45.00 -> 40.50
till 3.15 receipt coffee 3.50 -> 3.15
-- after: every customer --
regular 19.99 45.00 3.50
member 17.99 40.50 3.15
student 17.99 40.50 3.50
staff 14.99 40.00 2.62

The old till charged 18.00 for the novel while its receipt said 17.99. In the new design, both say 17.99. Note that the till’s price changed by a cent: removing duplicated knowledge means choosing one rounding rule, and the people who own the rule must know which. The new rule (round the discount to the nearest cent) is a third rounding, not a copy of either old one, and it moves a few other prices by a cent too: compared with the old merged function, the staff novel goes from 15.00 to 14.99, the staff coffee from 2.63 to 2.62, and the student novel from 18.00 to 17.99. That is a business decision to agree before release, not a detail to discover afterwards.

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

test_pricing.cpp
// LLD_TEST(name) defines one test, and LLD_CHECK(condition) records a
// failure if the condition is false. They come from the site's small test
// header, lld_test.hpp.
// The old till and receipt disagree by a cent: one rule, two roundings.
LLD_TEST(the_old_till_and_receipt_disagree) {
const Item novel{"novel", 1999, Category::book};
LLD_CHECK(before::till_member_price(novel.price_cents) == 1800);
LLD_CHECK(before::receipt_member_line(novel) == "novel 19.99 -> 17.99");
}
// For several prices, including tiny ones (1 and 5 cents) and a large one,
// the receipt shows exactly the price the till charges. The expected text
// is built from till_price itself, so the test checks agreement, not one
// particular number.
LLD_TEST(the_till_and_receipt_now_agree) {
for (const int cents : {1, 5, 1999, 4500, 350, 99999}) {
const Item item{"x", cents, Category::book};
LLD_CHECK(receipt_line(item, Customer::member) ==
"x " + euros(cents) + " -> " + euros(till_price(item, Customer::member)));
}
}
// The rounding rule at its edges: a discount of 0.5 of a cent rounds up
// to 1, and 0.4 of a cent rounds down to 0. The comments give the exact
// discount before rounding, in cents.
LLD_TEST(percent_of_rounds_half_a_cent_up) {
LLD_CHECK(percent_of(1999, 10) == 200); // 199.9
LLD_CHECK(percent_of(5, 10) == 1); // 0.5
LLD_CHECK(percent_of(4, 10) == 0); // 0.4
}
// 10% off a 45.00 book (4500 - 450 = 4050), nothing off a cafe item.
// {"atlas", 4500, Category::book} builds a temporary Item in place.
LLD_TEST(students_get_money_off_books_only) {
LLD_CHECK(student_price({"atlas", 4500, Category::book}) == 4050);
LLD_CHECK(student_price({"coffee", 350, Category::cafe}) == 350);
}
// Under the cap, 25% of 400 is 100 off. Over it, 25% of 4500 would be
// 1125 off, but the cap allows only 500.
LLD_TEST(staff_discount_is_capped_at_five_euros) {
LLD_CHECK(staff_price({"coffee", 400, Category::cafe}) == 300);
LLD_CHECK(staff_price({"atlas", 4500, Category::book}) == 4000); // 11.25 off, capped at 5.00
}
// Where the old code used the same rounding, the new rules give the same
// answers: merging and splitting changed the structure, not the prices.
// The two prices are chosen so that no discount has a fraction of a cent
// (10% and 25% of 4500 and of 400 are whole numbers), so the old rounding
// down and the new rounding to the nearest cent give the same result.
// Every item is tried with every kind of customer: 2 x 4 = 8 checks.
LLD_TEST(the_new_rules_match_the_old_where_both_round_alike) {
const std::vector<Item> items{{"atlas", 4500, Category::book}, {"coffee", 400, Category::cafe}};
for (const Item& item : items) {
for (const Customer c : {Customer::regular, Customer::member, Customer::student, Customer::staff}) {
LLD_CHECK(price_for(item, c) == before::price_for(item, c));
}
}
}

The first test pins down the old bug, so the page’s claim about it is checked. The last test compares the new rules with the old merged function on prices where both round the same way (the atlas, and a coffee at 4.00), which shows that splitting the wrong abstraction changed only the rounding, which was a deliberate decision, and not the rules themselves.

When should similar code be merged? A common rule of thumb: wait for the third copy. With two similar pieces of code, you rarely know yet whether they are the same knowledge or a coincidence. With three, the pattern (or its absence) is usually clear. Counting copies is only a heuristic, though: in this page’s story the three discounts were three copies and still should not have been merged. The ownership test (would they change together, for the same reason?) decides.

The rule of three is about similar code. It does not apply to duplicated knowledge: the till and receipt rule was wrong the moment it had two homes, and it should be fixed at once.

KISS: the simplest design that meets the real requirements

Section titled “KISS: the simplest design that meets the real requirements”

Here is a design that someone might propose for the same three discounts, as a sketch:

// A general rule engine, for three rules that change about once a year.
// Each rule is data, not code: who it is for, which items, how much.
struct DiscountRule {
std::string customer; // "member", "student", "staff"
std::string category; // "book", "cafe", or "*" for all
int percent = 0;
int cap_cents = -1; // -1: no cap
};
// Reads the rules from a configuration file (a format someone must design).
[[nodiscard]] std::vector<DiscountRule> load_rules(std::istream& config);
// Finds the rule that matches this customer and item, and applies it. The
// customer is now a string, so "membr" compiles and fails only at run time.
// std::span<const DiscountRule> is a read-only view of the loaded rules.
[[nodiscard]] int price_for(const Item& item, std::string_view customer,
std::span<const DiscountRule> rules);

It looks flexible. Count what it adds: a file format to define, parse, and test; customer and category names as strings, so a typo is found only when the program runs; questions nobody has asked yet (what if two rules match? do discounts stack?); and a cap value of -1 that means “none”. All of that, to express three rules that fit in about twenty lines of plain C++ with names the compiler checks.

KISS asks for the simplest design that meets the real requirements. Simple here means few moving parts and few concepts, not few lines. The three functions and a switch are simple. The rule engine is not.

KISS also has limits. It is not a reason to:

  • skip validation, error handling, or tests;
  • put everything in one function (that is easy to write, not simple to understand or change);
  • ignore a requirement that is already known.

The rule engine becomes the right design when a requirement calls for it: for example, if shop managers must change discounts without a new release, or if there are dozens of rules that marketing edits weekly. Then the data-driven design is meeting a requirement, and the complexity pays for itself. The composition and interfaces page shows a middle step: separate rule objects composed in code.

YAGNI is about features and extension points. Typical things to leave out of the bookshop:

Tempting now Why to wait
multiple currencies the shop is in one country; currency rules (rounding, display) are a project of their own
stacking discounts (“member and student”) nobody has asked; the shop may decide “best single discount” instead, and the guess would be wrong
a plugin interface for new discount kinds three rules, one development team; a new rule is one function and one case
discounts loaded from a database rules change yearly, with a release; see KISS above

Each of these costs code, tests, and documentation now, and each is a guess about the future. If the guess is wrong, the code is not just wasted; it is in the way of the design that the real requirement needs.

YAGNI is not a reason to write code that is hard to change. The difference:

  • Building for the future (YAGNI says no): code for multiple currencies, before anyone asks.
  • Keeping the design easy to change (always yes): each rule in one place, clear names, tests, concerns separated. This costs almost nothing now, and it is what makes adding a currency later a contained change.

A good design does not predict the future. It keeps the cost of the most likely changes low.

How the three rules pull against each other

Section titled “How the three rules pull against each other”
Tension Example How to decide
DRY against KISS merging three similar rules adds flags and a five-parameter function merge only shared knowledge; a little similar text is simpler than a wrong abstraction
DRY against YAGNI “let’s make one general discount function for all future rules” DRY covers rules you have; a general function for rules you might have is YAGNI
KISS against a known requirement “a switch is simpler than reading rules from a file” if managers must change rules without a release, the file is the requirement; KISS chooses among designs that meet it
  • DRY across boundaries. Two services, or two teams’ code, may each validate the same input. Sharing one validation library couples their releases. Some duplication across a boundary is a fair price for independence; make the shared contract (the rule as written down) the one source.
  • DRY in tests. Tests are easier to read when each one spells out its values. A helper that builds a common object is fine; a test that hides its expected values in a shared table is harder to trust.
  • KISS for a known, large requirement. If the shop will open in five countries next month, currency is a requirement, not speculation.
  • YAGNI for things that are expensive to add later. Some decisions are hard to reverse: a public file format, a database schema, the type used for money. It is worth thinking about those early, even if you build only what is needed today.
  • Merging look-alike code. Two functions with the same lines but different owners. Ask “who asks for changes?” before merging.
  • Flags to rescue a shared function. When a shared function gains bool parameters for each caller, it is a wrong abstraction. Split it.
  • Missing the duplicate that is written differently. cents - cents / 10 and cents * 90 / 100 are the same rule. Search for the meaning, not the text.
  • Calling a big design “simple” because it is general. Generality is a cost unless a requirement uses it.
  • Using YAGNI to skip structure. “We do not need tests or separation yet” is not YAGNI; it is debt.

Members get 15% off books, and still 10% off café items. In the new design, only member_price changes; the student and staff rules, the rounding, and both callers are untouched. A sketch (syntax-checked, but not part of the example):

int member_price(const Item& item) {
// ?: reads "if a book, 15, otherwise 10".
const int percent = item.category == Category::book ? 15 : 10;
return item.price_cents - percent_of(item.price_cents, percent);
}

In the old merged function, the member call site could pass item.category == Category::book ? 15 : 10 as the percentage. That works, but the member rule is now split: the category choice sits in price_for, next to the flags of the other rules, and the rounding and the “regular pays full price” check sit in the shared function. The next member change (“a flat 1.00 off on café items”) does not fit at all without a new mode parameter, which every caller must pass. Either way, a change for one owner touches code that all three owners depend on.

Exercise: Merge three similar functions?

A library has three late-fee functions:

// Each: 20 cents for every day late, but never more than 1000 cents
// (10.00). std::min returns the smaller of its two arguments.
int late_fee_books(int days) { return std::min(days * 20, 1000); }
int late_fee_dvds(int days) { return std::min(days * 20, 1000); }
int late_fee_laptops(int days) { return std::min(days * 20, 1000); }

What you learn by asking around:

  • Books and DVDs follow the city council’s lending policy, which says one fee applies to “all books and DVDs”. The council reviews it every year.
  • Laptop fees come from the library’s insurance contract for its laptops. They happen to match the council’s numbers today.
  1. Which of the three, if any, should share one function? Why?
  2. Write the result.
  3. The council raises its daily fee to 25 cents. Which functions change?
Show the explained answer

1. Books and DVDs should share one function: they express the same knowledge, the council’s policy, and the policy itself says one fee applies to all books and DVDs. When the council changes it, both must change together. Laptops should stay separate: the numbers match by coincidence, the owner is different (the insurance contract), and the reason to change is different. Merging all three would be a wrong abstraction.

2.

// The council's lending policy, reviewed yearly. constexpr: fixed when
// compiling. inline: one shared constant, even if a header holding it is
// included by many files.
inline constexpr int council_cents_per_day = 20;
inline constexpr int council_max_cents = 1000;
[[nodiscard]] int standard_late_fee(int days_late) {
return std::min(days_late * council_cents_per_day, council_max_cents);
}
// From the laptop insurance contract; matches the council by coincidence.
[[nodiscard]] int laptop_late_fee(int days_late) {
constexpr int cents_per_day = 20; // insurance contract, clause 4
constexpr int max_cents = 1000;
return std::min(days_late * cents_per_day, max_cents);
}

Books and DVDs both call standard_late_fee. The names say whose rule each one is, and the comment on the laptop fee warns the next reader not to “fix” the duplication. (A real program would also decide what a negative days_late means; here it is assumed to be 0 or more.)

3. Only one constant changes: the council’s daily fee (its maximum stays 10.00). Books and DVDs get the new fee; laptops keep theirs, as the contract requires. With all three merged, the laptop fee would have changed too, silently breaking the contract.

  • DRY means one home for each piece of knowledge. Duplicated knowledge is a bug waiting to happen, as the till and receipt showed.
  • Similar code is not always the same knowledge. Merging coincidental similarity creates a wrong abstraction, usually recognisable by its flags. Undo it by splitting.
  • Ask who asks for changes to decide which is which. Wait for a third copy before merging look-alike code; fix duplicated knowledge at once.
  • KISS means the fewest moving parts that meet the real requirements, not the fewest lines, and not skipping tests.
  • YAGNI means not building features nobody asked for. It does not mean making code hard to change; good structure is what makes later features cheap.