DRY, KISS & YAGNI — and When They Conflict
These three acronyms are the most quoted design advice there is, and probably the most misapplied. "Don't repeat yourself" gets used to justify a helper with six boolean flags. "Keep it simple" gets used to excuse a 300-line method. "You aren't gonna need it" gets used to reject an interface the interviewer asked for two minutes earlier. Each principle is sound. Each turns harmful when you apply it to the wrong thing, and they regularly pull in opposite directions.
This page treats them as tools for one job: keeping the cost of the next change low. Duplication raises that cost when the copies must change together. Complexity raises it because every reader pays to understand the code. Speculative features raise it because you carry code that nobody uses and that gets in the way of the change you actually need. Once you see all three as cost arguments, the conflicts become trade-offs you can reason about rather than slogans you have to pick between.
| Principle | What it really says | What it does not say |
|---|---|---|
| DRY | Each piece of knowledge has one authoritative home | "Never write two similar-looking lines" |
| KISS | Prefer the design with the fewest moving parts that meets the requirements | "Prefer the design with the fewest lines" or "never add a class" |
| YAGNI | Don't build features before there's a requirement for them | "Never make code easy to extend" |
The Java samples use a small check helper instead of assert, so they fail loudly without the -ea flag. Every sample on this page was run with Java 24, Python 3.12 and TypeScript 5.8 (tsc --strict, then tsx).
1. Why these three belong together
SOLID is mostly about where to draw boundaries: which class owns which responsibility, which way dependencies point. DRY, KISS and YAGNI are about how much design to do. They're dials, and the right setting depends on how likely change is and how expensive it would be.
- Turn DRY up too far and you merge things that only look alike, so changing one breaks the other.
- Turn KISS up too far and you refuse every abstraction, so one function absorbs every rule.
- Turn YAGNI up too far and you paint yourself into a corner, refusing even the cheap seam a known requirement needs.
- Turn all three down and you get the opposite failures: copy-paste drift, clever frameworks, and speculative plug-in systems.
In an LLD interview, these dials are visible within the first ten minutes. The interviewer sees whether you build a PaymentStrategyFactoryProvider for a single payment method (YAGNI too low), whether pricing is computed in three places (DRY too low), and whether you can explain your design in two sentences (KISS). The scoring rubric rewards candidates who set the dials on purpose and say why.
2. DRY: knowledge, not text
Andy Hunt and Dave Thomas introduced DRY in The Pragmatic Programmer (1999) with a precise definition: every piece of knowledge must have a single, unambiguous, authoritative representation within a system. The word that matters is knowledge. DRY isn't about characters on the screen. Two identical lines can be fine, and two different-looking functions can be a DRY violation if they encode the same business rule.
A useful test is to ask: if this rule changes, how many places must I edit, and will I remember all of them? If the answer is "more than one, and probably not", you have duplicated knowledge.
2.1 True duplication
Here's the classic case. A shop gives 10% off orders of 500.00 or more. The rule appears in the cart (so the customer sees the discounted total) and in the invoice (so they're billed it). The threshold used to be 1,000.00. Someone updated the cart and forgot the invoice. The two copies also round differently, because each author wrote the arithmetic their own way, so even when the thresholds agreed the totals could differ by a cent.
import java.util.*;
// ---------- before: the discount rule lives in two places ----------
final class CartBefore {
private final List<Long> itemCents = new ArrayList<>();
void add(long cents) { itemCents.add(cents); }
long totalCents() {
long sum = itemCents.stream().mapToLong(Long::longValue).sum();
if (sum >= 50_000) sum -= sum / 10; // updated when the threshold dropped to 500.00
return sum;
}
}
final class InvoiceBefore {
static long amountDue(List<Long> lineCents) {
long sum = 0;
for (long c : lineCents) sum += c;
if (sum >= 100_000) sum = sum * 9 / 10; // the old rule, and different rounding
return sum;
}
}
// ---------- after: one authoritative home for the rule ----------
final class Discount {
static final long THRESHOLD_CENTS = 50_000;
private Discount() {}
static long apply(long subtotalCents) {
return subtotalCents >= THRESHOLD_CENTS ? subtotalCents - subtotalCents / 10 : subtotalCents;
}
}
final class Cart {
private final List<Long> itemCents = new ArrayList<>();
void add(long cents) { itemCents.add(cents); }
long totalCents() { return Discount.apply(itemCents.stream().mapToLong(Long::longValue).sum()); }
}
final class Invoice {
static long amountDue(List<Long> lineCents) {
return Discount.apply(lineCents.stream().mapToLong(Long::longValue).sum());
}
}
class TrueDuplicationDemo {
static void check(boolean ok, String what) { if (!ok) throw new AssertionError(what); }
public static void main(String[] args) {
CartBefore oldCart = new CartBefore();
oldCart.add(40_000); oldCart.add(20_000); // 600.00
long shown = oldCart.totalCents();
long billed = InvoiceBefore.amountDue(List.of(40_000L, 20_000L));
check(shown == 54_000 && billed == 60_000, "before: the copies disagree");
for (long subtotal : new long[] {49_999, 50_000, 50_005, 123_457}) {
Cart cart = new Cart();
cart.add(subtotal);
check(cart.totalCents() == Invoice.amountDue(List.of(subtotal)), "after: always agree");
}
System.out.println("before: saw " + shown + ", billed " + billed + ". after: consistent");
}
}
# ---------- before: the discount rule lives in two places ----------
class CartBefore:
def __init__(self) -> None:
self._items: list[int] = []
def add(self, cents: int) -> None:
self._items.append(cents)
def total_cents(self) -> int:
total = sum(self._items)
if total >= 50_000: # updated when the threshold dropped to 500.00
total -= total // 10
return total
def invoice_amount_due_before(lines: list[int]) -> int:
total = sum(lines)
if total >= 100_000: # the old rule, and different rounding
total = total * 9 // 10
return total
# ---------- after: one authoritative home for the rule ----------
DISCOUNT_THRESHOLD_CENTS = 50_000
def apply_discount(subtotal_cents: int) -> int:
if subtotal_cents >= DISCOUNT_THRESHOLD_CENTS:
return subtotal_cents - subtotal_cents // 10
return subtotal_cents
class Cart:
def __init__(self) -> None:
self._items: list[int] = []
def add(self, cents: int) -> None:
self._items.append(cents)
def total_cents(self) -> int:
return apply_discount(sum(self._items))
def invoice_amount_due(lines: list[int]) -> int:
return apply_discount(sum(lines))
old = CartBefore()
old.add(40_000)
old.add(20_000)
assert old.total_cents() == 54_000
assert invoice_amount_due_before([40_000, 20_000]) == 60_000 # the customer is overbilled
for subtotal in (49_999, 50_000, 50_005, 123_457):
cart = Cart()
cart.add(subtotal)
assert cart.total_cents() == invoice_amount_due([subtotal])
print("before: copies disagree. after: consistent")
function check(ok: boolean, what: string): void {
if (!ok) throw new Error(what);
}
// ---------- before: the discount rule lives in two places ----------
class CartBefore {
private readonly items: number[] = [];
add(cents: number): void { this.items.push(cents); }
totalCents(): number {
let total = this.items.reduce((a, b) => a + b, 0);
if (total >= 50_000) total -= Math.floor(total / 10); // updated when the threshold dropped
return total;
}
}
function invoiceAmountDueBefore(lines: number[]): number {
let total = lines.reduce((a, b) => a + b, 0);
if (total >= 100_000) total = Math.floor((total * 9) / 10); // the old rule, different rounding
return total;
}
// ---------- after: one authoritative home for the rule ----------
const DISCOUNT_THRESHOLD_CENTS = 50_000;
function applyDiscount(subtotalCents: number): number {
return subtotalCents >= DISCOUNT_THRESHOLD_CENTS
? subtotalCents - Math.floor(subtotalCents / 10)
: subtotalCents;
}
class Cart {
private readonly items: number[] = [];
add(cents: number): void { this.items.push(cents); }
totalCents(): number { return applyDiscount(this.items.reduce((a, b) => a + b, 0)); }
}
const invoiceAmountDue = (lines: number[]): number => applyDiscount(lines.reduce((a, b) => a + b, 0));
const old = new CartBefore();
old.add(40_000);
old.add(20_000);
check(old.totalCents() === 54_000 && invoiceAmountDueBefore([40_000, 20_000]) === 60_000, "copies disagree");
for (const subtotal of [49_999, 50_000, 50_005, 123_457]) {
const cart = new Cart();
cart.add(subtotal);
check(cart.totalCents() === invoiceAmountDue([subtotal]), "after: always agree");
}
console.log("before: copies disagree. after: consistent");
Notice that the "before" copies don't even look identical: one subtracts a tenth, the other multiplies by nine-tenths. A text-matching duplicate detector wouldn't flag them. That's why DRY is about knowledge. The rule "orders of 500.00 or more get 10% off, rounding in the customer's favour" was written down twice, so it could drift, and it did.
2.2 Incidental duplication
Now the opposite case. A sign-up form has a username and a display name, and today both must be 3 to 20 characters. The code for checking them is identical, so a well-meaning refactor merges it into one validName function. A month later, product decides display names can be up to 50 characters and may contain spaces. The developer edits the shared function, and usernames silently start accepting 50 characters too.
The two checks looked the same, but they encode different knowledge that happened to coincide. Usernames are constrained by URLs and database keys. Display names are constrained by what fits on a profile card. They change for different reasons and are owned by different people. Robert C. Martin calls this accidental duplication. The test is the same as before, run in the other direction: if one changes, must the other change too? If not, merging them couples two things that should be free to diverge.
// ---------- before: two different rules merged because they looked alike ----------
final class NameRules {
private NameRules() {}
// Raised to 50 and spaces allowed "for display names". Usernames silently changed too.
static boolean validName(String s) { return s.length() >= 3 && s.length() <= 50; }
}
// ---------- after: each rule owns its own knowledge ----------
final class Username {
static boolean isValid(String s) { return s.matches("[a-z0-9_]{3,20}"); }
}
final class DisplayName {
static boolean isValid(String s) {
String trimmed = s.strip();
return trimmed.length() >= 3 && trimmed.length() <= 50;
}
}
class IncidentalDuplicationDemo {
static void check(boolean ok, String what) { if (!ok) throw new AssertionError(what); }
public static void main(String[] args) {
String longHandle = "a".repeat(40);
check(NameRules.validName(longHandle), "before: a 40-char username slips through");
check(NameRules.validName("Ada Lovelace"), "before: spaces allowed for usernames too");
check(!Username.isValid(longHandle), "after: usernames still max 20");
check(!Username.isValid("Ada Lovelace"), "after: usernames have no spaces");
check(DisplayName.isValid("Ada Lovelace, Countess of Lovelace"), "after: display names grew");
System.out.println("incidental duplication kept apart");
}
}
import re
# ---------- before: two different rules merged because they looked alike ----------
def valid_name(s: str) -> bool:
# Raised to 50 and spaces allowed "for display names". Usernames silently changed too.
return 3 <= len(s) <= 50
# ---------- after: each rule owns its own knowledge ----------
USERNAME = re.compile(r"[a-z0-9_]{3,20}")
def is_valid_username(s: str) -> bool:
return USERNAME.fullmatch(s) is not None
def is_valid_display_name(s: str) -> bool:
return 3 <= len(s.strip()) <= 50
long_handle = "a" * 40
assert valid_name(long_handle) # before: a 40-char username slips through
assert valid_name("Ada Lovelace") # before: spaces allowed in usernames
assert not is_valid_username(long_handle)
assert not is_valid_username("Ada Lovelace")
assert is_valid_display_name("Ada Lovelace, Countess of Lovelace")
print("incidental duplication kept apart")
function check(ok: boolean, what: string): void {
if (!ok) throw new Error(what);
}
// ---------- before: two different rules merged because they looked alike ----------
// Raised to 50 and spaces allowed "for display names". Usernames silently changed too.
const validName = (s: string): boolean => s.length >= 3 && s.length <= 50;
// ---------- after: each rule owns its own knowledge ----------
const isValidUsername = (s: string): boolean => /^[a-z0-9_]{3,20}$/.test(s);
const isValidDisplayName = (s: string): boolean => {
const t = s.trim();
return t.length >= 3 && t.length <= 50;
};
const longHandle = "a".repeat(40);
check(validName(longHandle), "before: a 40-char username slips through");
check(validName("Ada Lovelace"), "before: spaces allowed in usernames");
check(!isValidUsername(longHandle), "after: usernames still max 20");
check(!isValidUsername("Ada Lovelace"), "after: no spaces in usernames");
check(isValidDisplayName("Ada Lovelace, Countess of Lovelace"), "after: display names grew");
console.log("incidental duplication kept apart");
The "after" code has more lines than the merged version, and that's the right call. Two five-line functions that can change independently are cheaper than one five-line function that forces them to change together.
2.3 Telling them apart
When you spot two similar pieces of code, run through these questions before you extract anything:
| Question | Points to true duplication | Points to incidental duplication |
|---|---|---|
| If one changes, must the other? | Yes, always | Not necessarily |
| Who asks for changes? | The same person or team | Different stakeholders |
| Can you name the shared concept? | Easily: "the discount rule", "the late-fee policy" | Only generically: "validate string", "process item" |
| Why are they the same today? | Because the business rule is the same | Coincidence, or copy-paste as a starting point |
| What does the merged version need? | No flags, same parameters everywhere | Flags or optional parameters appear quickly |
The naming test is the quickest. If the best name you can find for the shared function is generic (process, handle, validateString, Utils.doCommon), you probably haven't found a concept. You've found a coincidence.
2.4 The rule of three
When you aren't sure, the rule of three is a practical default (Martin Fowler credits it to Don Roberts in Refactoring). The first time, just write it. The second time, wince at the duplication but write it again. The third time, refactor. By the third occurrence you have three real examples to generalise from, so you can see which parts actually vary. With two, you're guessing, and a guess is how the wrong abstraction gets in.
The rule of three is a heuristic for incidental-looking code. For a business rule that you know is one rule, like the discount above, extract it on the second occurrence. You aren't guessing what varies there. The domain already told you.
2.5 DRY beyond functions
Knowledge lives in more places than method bodies, and duplication in these places is often worse because no compiler checks it:
- Magic numbers. The same
0.18tax rate in four files. Give it a name and one home. - Parallel enums and switches. A
VehicleTypeenum plus aswitchon it in the pricing class, the allocation class and the display class. Each new type means finding every switch. This is the leaky enum mistake. - Schemas and types. A request DTO, a domain class and a database row that all describe the same shape by hand. Generating one from another, or mapping in one place, keeps them aligned.
- Comments that restate code.
// add 1 to countabovecount++is duplicated knowledge too. When the code changes, the comment lies.
3. The wrong abstraction
Sandi Metz put the cost of over-applying DRY bluntly in a 2016 essay: duplication is far cheaper than the wrong abstraction. Her description of how it happens is worth paraphrasing because nearly every codebase has an example:
- A programmer sees duplication and extracts it into a shared function. It's a good abstraction at that point.
- A new requirement is almost covered by the abstraction. The next programmer adds a parameter and a conditional rather than question it.
- This repeats. Each addition is small. Each programmer assumes the abstraction must be right because it already exists.
- The function now takes several flags, its branches interact, and nobody can change it without understanding every caller.
The sunk cost of the existing abstraction makes it feel expensive to undo. It's actually cheap. Inline the abstraction back into every caller, delete the branches each caller doesn't use, and then look for the real duplication again. You'll usually find a much smaller shared piece, if any.
Here's a receipt renderer after three rounds of "just add a flag". It started as a shared function for in-store and online receipts.
import java.util.*;
record Line(String name, long cents) {}
// ---------- before: one function, three flags, interacting branches ----------
final class ReceiptRenderer {
static String render(List<Line> lines, boolean html, boolean gift, boolean showTax) {
StringBuilder out = new StringBuilder(html ? "<ul>" : "");
long total = 0;
for (Line l : lines) {
total += l.cents();
String price = gift ? "" : " " + money(l.cents()); // gift receipts hide prices
out.append(html ? "<li>" + l.name() + price + "</li>" : l.name() + price + "\n");
}
if (html) out.append("</ul>");
if (showTax && !gift) out.append(html ? "<p>tax " : "tax ").append(money(total * 18 / 100));
return out.toString();
}
static String money(long cents) { return String.format("%d.%02d", cents / 100, cents % 100); }
}
// ---------- after: three small renderers, one genuinely shared helper ----------
final class Money {
private Money() {}
static String format(long cents) { return String.format("%d.%02d", cents / 100, cents % 100); }
}
final class StoreReceipt {
static String render(List<Line> lines) {
StringBuilder out = new StringBuilder();
long total = 0;
for (Line l : lines) { total += l.cents(); out.append(l.name()).append(' ').append(Money.format(l.cents())).append('\n'); }
return out.append("tax ").append(Money.format(total * 18 / 100)).toString();
}
}
final class GiftReceipt {
static String render(List<Line> lines) {
StringBuilder out = new StringBuilder();
for (Line l : lines) out.append(l.name()).append('\n');
return out.toString();
}
}
final class EmailReceipt {
static String render(List<Line> lines) {
StringBuilder out = new StringBuilder("<ul>");
for (Line l : lines) out.append("<li>").append(l.name()).append(' ').append(Money.format(l.cents())).append("</li>");
return out.append("</ul>").toString();
}
}
class WrongAbstractionDemo {
static void check(boolean ok, String what) { if (!ok) throw new AssertionError(what); }
public static void main(String[] args) {
List<Line> lines = List.of(new Line("tea", 250), new Line("cake", 400));
check(ReceiptRenderer.render(lines, false, false, true).equals(StoreReceipt.render(lines)), "store");
check(ReceiptRenderer.render(lines, false, true, false).equals(GiftReceipt.render(lines)), "gift");
check(ReceiptRenderer.render(lines, true, false, false).equals(EmailReceipt.render(lines)), "email");
check(StoreReceipt.render(lines).endsWith("tax 1.17"), "18% of 6.50, rounded down");
System.out.println(StoreReceipt.render(lines));
}
}
from dataclasses import dataclass
@dataclass(frozen=True)
class Line:
name: str
cents: int
def money(cents: int) -> str:
return f"{cents // 100}.{cents % 100:02d}"
# ---------- before: one function, three flags, interacting branches ----------
def render(lines: list[Line], html: bool, gift: bool, show_tax: bool) -> str:
out = "<ul>" if html else ""
total = 0
for line in lines:
total += line.cents
price = "" if gift else " " + money(line.cents)
out += f"<li>{line.name}{price}</li>" if html else f"{line.name}{price}\n"
if html:
out += "</ul>"
if show_tax and not gift:
out += ("<p>tax " if html else "tax ") + money(total * 18 // 100)
return out
# ---------- after: three small renderers, one genuinely shared helper ----------
def store_receipt(lines: list[Line]) -> str:
body = "".join(f"{l.name} {money(l.cents)}\n" for l in lines)
return body + "tax " + money(sum(l.cents for l in lines) * 18 // 100)
def gift_receipt(lines: list[Line]) -> str:
return "".join(f"{l.name}\n" for l in lines)
def email_receipt(lines: list[Line]) -> str:
return "<ul>" + "".join(f"<li>{l.name} {money(l.cents)}</li>" for l in lines) + "</ul>"
items = [Line("tea", 250), Line("cake", 400)]
assert render(items, html=False, gift=False, show_tax=True) == store_receipt(items)
assert render(items, html=False, gift=True, show_tax=False) == gift_receipt(items)
assert render(items, html=True, gift=False, show_tax=False) == email_receipt(items)
assert store_receipt(items).endswith("tax 1.17")
print(store_receipt(items))
function check(ok: boolean, what: string): void {
if (!ok) throw new Error(what);
}
interface Line { readonly name: string; readonly cents: number }
const money = (cents: number): string =>
`${Math.floor(cents / 100)}.${String(cents % 100).padStart(2, "0")}`;
// ---------- before: one function, three flags, interacting branches ----------
function render(lines: Line[], html: boolean, gift: boolean, showTax: boolean): string {
let out = html ? "<ul>" : "";
let total = 0;
for (const l of lines) {
total += l.cents;
const price = gift ? "" : " " + money(l.cents);
out += html ? `<li>${l.name}${price}</li>` : `${l.name}${price}\n`;
}
if (html) out += "</ul>";
if (showTax && !gift) out += (html ? "<p>tax " : "tax ") + money(Math.floor((total * 18) / 100));
return out;
}
// ---------- after: three small renderers, one genuinely shared helper ----------
const storeReceipt = (lines: Line[]): string =>
lines.map((l) => `${l.name} ${money(l.cents)}\n`).join("") +
"tax " + money(Math.floor((lines.reduce((s, l) => s + l.cents, 0) * 18) / 100));
const giftReceipt = (lines: Line[]): string => lines.map((l) => `${l.name}\n`).join("");
const emailReceipt = (lines: Line[]): string =>
"<ul>" + lines.map((l) => `<li>${l.name} ${money(l.cents)}</li>`).join("") + "</ul>";
const items: Line[] = [{ name: "tea", cents: 250 }, { name: "cake", cents: 400 }];
check(render(items, false, false, true) === storeReceipt(items), "store");
check(render(items, false, true, false) === giftReceipt(items), "gift");
check(render(items, true, false, false) === emailReceipt(items), "email");
check(storeReceipt(items).endsWith("tax 1.17"), "18% of 6.50");
console.log(storeReceipt(items));
Three flags means eight combinations, and only three are ever used. The others, like an HTML gift receipt with tax, are reachable and untested. Notice that one of them has a bug nobody will see until someone calls it: an HTML receipt with tax opens a <p> and never closes it. After the split, each renderer reads top to bottom with no branches, and the only shared piece is money, which is real shared knowledge: how this shop formats an amount.
Flag arguments are a smell
A boolean parameter that selects between two behaviours (render(lines, true, false, true)) usually means the function does two jobs. Callers can't read it without looking up the signature. Splitting into two named functions, or passing a strategy when the behaviours genuinely vary at runtime, almost always reads better.
4. KISS: fewest moving parts
"Keep it simple, stupid" is usually traced to Kelly Johnson, lead engineer at Lockheed's Skunk Works, who wanted jet aircraft that an average mechanic could repair in the field with basic tools. The point wasn't that the aircraft should be primitive. It was that complexity has to justify itself against the people who'll maintain the thing under pressure.
In code, those people are the next engineer and you at 3 a.m. KISS asks: of the designs that meet the requirements, which has the fewest concepts someone must hold in their head?
4.1 Simple is not the same as short or easy
Rich Hickey's 2011 talk Simple Made Easy separates two words people use interchangeably:
- Simple means not intertwined: one role, one concept, few connections. It's a property of the design.
- Easy means near at hand: familiar, quick to type, already installed. It's a property of your situation.
A one-line stream pipeline with three nested lambdas is short and might be easy for its author. It isn't simple if it braids filtering, grouping and side effects together. Five small classes with one job each can be simpler than one class with a long method, because each piece can be understood alone. KISS doesn't mean fewer classes. It means fewer things tangled with each other.
4.2 Over-engineered versus simple
A library charges late fees: nothing for the first 2 days, then 0.50 a day, capped at 20.00. Here's a "flexible" version that models fees as a prioritised rule chain with string keys, and a simple version that reads like the requirement.
import java.util.*;
import java.util.function.*;
// ---------- before: a general rule engine for one fee formula ----------
final class FeeRule {
final String name; final int priority; final Predicate<Map<String, Long>> when;
final BiFunction<Map<String, Long>, Long, Long> then;
FeeRule(String name, int priority, Predicate<Map<String, Long>> when, BiFunction<Map<String, Long>, Long, Long> then) {
this.name = name; this.priority = priority; this.when = when; this.then = then;
}
}
final class FeeEngine {
private final List<FeeRule> rules = new ArrayList<>();
FeeEngine register(FeeRule r) { rules.add(r); rules.sort(Comparator.comparingInt(x -> x.priority)); return this; }
long evaluate(Map<String, Long> ctx) {
long fee = 0;
for (FeeRule r : rules) if (r.when.test(ctx)) fee = r.then.apply(ctx, fee);
return fee;
}
}
// ---------- after: the requirement, written down ----------
final class LateFee {
static final int GRACE_DAYS = 2;
static final long CENTS_PER_DAY = 50, CAP_CENTS = 2_000;
private LateFee() {}
static long cents(int daysLate) {
long chargeable = Math.max(0, daysLate - GRACE_DAYS);
return Math.min(chargeable * CENTS_PER_DAY, CAP_CENTS);
}
}
class KissDemo {
static void check(boolean ok, String what) { if (!ok) throw new AssertionError(what); }
public static void main(String[] args) {
FeeEngine engine = new FeeEngine()
.register(new FeeRule("daily", 10, c -> c.get("daysLate") > 2, (c, f) -> (c.get("daysLate") - 2) * 50))
.register(new FeeRule("cap", 20, c -> true, (c, f) -> Math.min(f, 2_000)));
for (int days : new int[] {0, 2, 3, 10, 42, 400}) {
long viaEngine = engine.evaluate(Map.of("daysLate", (long) days));
check(viaEngine == LateFee.cents(days), "same answer for " + days);
}
check(LateFee.cents(3) == 50 && LateFee.cents(42) == 2_000, "spot checks");
System.out.println("same behaviour, a fraction of the concepts");
}
}
from dataclasses import dataclass
from typing import Callable
Ctx = dict[str, int]
# ---------- before: a general rule engine for one fee formula ----------
@dataclass
class FeeRule:
name: str
priority: int
when: Callable[[Ctx], bool]
then: Callable[[Ctx, int], int]
class FeeEngine:
def __init__(self) -> None:
self._rules: list[FeeRule] = []
def register(self, rule: FeeRule) -> "FeeEngine":
self._rules.append(rule)
self._rules.sort(key=lambda r: r.priority)
return self
def evaluate(self, ctx: Ctx) -> int:
fee = 0
for rule in self._rules:
if rule.when(ctx):
fee = rule.then(ctx, fee)
return fee
# ---------- after: the requirement, written down ----------
GRACE_DAYS, CENTS_PER_DAY, CAP_CENTS = 2, 50, 2_000
def late_fee_cents(days_late: int) -> int:
return min(max(0, days_late - GRACE_DAYS) * CENTS_PER_DAY, CAP_CENTS)
engine = (FeeEngine()
.register(FeeRule("daily", 10, lambda c: c["days"] > 2, lambda c, f: (c["days"] - 2) * 50))
.register(FeeRule("cap", 20, lambda c: True, lambda c, f: min(f, 2_000))))
for days in (0, 2, 3, 10, 42, 400):
assert engine.evaluate({"days": days}) == late_fee_cents(days)
assert late_fee_cents(3) == 50 and late_fee_cents(42) == 2_000
print("same behaviour, a fraction of the concepts")
function check(ok: boolean, what: string): void {
if (!ok) throw new Error(what);
}
type Ctx = Record<string, number>;
// ---------- before: a general rule engine for one fee formula ----------
interface FeeRule {
name: string;
priority: number;
when: (c: Ctx) => boolean;
then: (c: Ctx, fee: number) => number;
}
class FeeEngine {
private readonly rules: FeeRule[] = [];
register(rule: FeeRule): this {
this.rules.push(rule);
this.rules.sort((a, b) => a.priority - b.priority);
return this;
}
evaluate(ctx: Ctx): number {
return this.rules.reduce((fee, r) => (r.when(ctx) ? r.then(ctx, fee) : fee), 0);
}
}
// ---------- after: the requirement, written down ----------
const GRACE_DAYS = 2, CENTS_PER_DAY = 50, CAP_CENTS = 2_000;
const lateFeeCents = (daysLate: number): number =>
Math.min(Math.max(0, daysLate - GRACE_DAYS) * CENTS_PER_DAY, CAP_CENTS);
const engine = new FeeEngine()
.register({ name: "daily", priority: 10, when: (c) => (c.days ?? 0) > 2, then: (c) => ((c.days ?? 0) - 2) * 50 })
.register({ name: "cap", priority: 20, when: () => true, then: (_c, f) => Math.min(f, 2_000) });
for (const days of [0, 2, 3, 10, 42, 400]) {
check(engine.evaluate({ days }) === lateFeeCents(days), `same answer for ${days}`);
}
check(lateFeeCents(3) === 50 && lateFeeCents(42) === 2_000, "spot checks");
console.log("same behaviour, a fraction of the concepts");
Both give the same answers. The engine also makes the code harder to change correctly. To change the grace period, you edit a magic 2 that appears twice inside lambdas, and the rules' order is controlled by priority numbers that someone has to keep in their head. The simple version puts each number in one named constant. If the library later needs member-tier discounts and holiday waivers configured by staff at runtime, a rule engine might earn its place. Until then it's machinery without a job.
4.3 Signals that something isn't simple
- You need a diagram to explain a feature that the requirement describes in one sentence.
- A name contains
Manager,Processor,Engine,FrameworkorGenericand you can't say what it decides. - Reflection, dynamic class loading, string-keyed lookups or metaprogramming appear in business logic.
- Generic type parameters nest more than one deep (
Handler<Event<Payload<T>>>). - Adding a new case means editing configuration and a registry and a class.
- The happy path is hard to find among the extension hooks.
5. YAGNI: features follow requirements
"You aren't gonna need it" comes from Extreme Programming in the late 1990s. Ron Jeffries' version is: always implement things when you actually need them, never when you just foresee that you need them. Martin Fowler's 2015 article on YAGNI breaks down why building a presumptive feature costs more than it seems, even if you turn out to be right:
| Cost | What it means |
|---|---|
| Cost of build | The time spent building, testing and reviewing the speculative feature, instead of something needed now |
| Cost of delay | The needed features ship later because of it |
| Cost of carry | Every future change must work around the extra code. It's more to read, test and keep compatible |
| Cost of repair | When the real requirement arrives, it's rarely exactly what you guessed, so you rework it anyway |
If the guess is wrong, you pay build, delay and carry, then delete it. If the guess is right, you still pay delay and carry, and usually repair. Fowler's conclusion is that the presumptive feature has to be very likely and very expensive to add later before it's worth building now.
5.1 A speculative design
The requirement: show the top k players by score. The speculative version adds pluggable ranking strategies, a persistence hook, pagination and an event listener, all "in case".
import java.util.*;
import java.util.function.*;
// ---------- before: built for requirements nobody stated ----------
interface RankingStrategy { Comparator<Map.Entry<String, Integer>> order(); }
interface ScoreStore { void persist(String player, int score); }
interface ScoreListener { void onScore(String player, int score); }
final class SpeculativeLeaderboard {
private final Map<String, Integer> scores = new HashMap<>();
private final RankingStrategy ranking;
private final ScoreStore store;
private final List<ScoreListener> listeners = new ArrayList<>();
SpeculativeLeaderboard(RankingStrategy ranking, ScoreStore store) { this.ranking = ranking; this.store = store; }
void addListener(ScoreListener l) { listeners.add(l); }
void submit(String player, int score) {
scores.merge(player, score, Math::max);
store.persist(player, score);
listeners.forEach(l -> l.onScore(player, score));
}
List<String> page(int pageNo, int pageSize) {
return scores.entrySet().stream().sorted(ranking.order())
.skip((long) pageNo * pageSize).limit(pageSize).map(Map.Entry::getKey).toList();
}
}
// ---------- after: what was asked for ----------
final class Leaderboard {
private final Map<String, Integer> best = new HashMap<>();
void submit(String player, int score) { best.merge(player, score, Math::max); }
List<String> top(int k) {
return best.entrySet().stream()
.sorted(Map.Entry.<String, Integer>comparingByValue().reversed().thenComparing(Map.Entry.comparingByKey()))
.limit(k).map(Map.Entry::getKey).toList();
}
}
class YagniDemo {
static void check(boolean ok, String what) { if (!ok) throw new AssertionError(what); }
public static void main(String[] args) {
Leaderboard board = new Leaderboard();
board.submit("ana", 40); board.submit("bo", 75); board.submit("ana", 90); board.submit("cy", 75);
check(board.top(2).equals(List.of("ana", "bo")), "best score per player, ties by name");
check(board.top(10).size() == 3, "k larger than the board");
SpeculativeLeaderboard heavy = new SpeculativeLeaderboard(
() -> Map.Entry.<String, Integer>comparingByValue().reversed().thenComparing(Map.Entry.comparingByKey()),
(p, s) -> {});
heavy.submit("ana", 40); heavy.submit("bo", 75); heavy.submit("ana", 90); heavy.submit("cy", 75);
check(heavy.page(0, 2).equals(board.top(2)), "same answer, three extra interfaces");
System.out.println(board.top(3));
}
}
from typing import Callable, Protocol
# ---------- before: built for requirements nobody stated ----------
class ScoreStore(Protocol):
def persist(self, player: str, score: int) -> None: ...
class SpeculativeLeaderboard:
def __init__(self, rank_key: Callable[[tuple[str, int]], object], store: ScoreStore) -> None:
self._scores: dict[str, int] = {}
self._rank_key = rank_key
self._store = store
self._listeners: list[Callable[[str, int], None]] = []
def add_listener(self, fn: Callable[[str, int], None]) -> None:
self._listeners.append(fn)
def submit(self, player: str, score: int) -> None:
self._scores[player] = max(score, self._scores.get(player, score))
self._store.persist(player, score)
for fn in self._listeners:
fn(player, score)
def page(self, page_no: int, size: int) -> list[str]:
ranked = sorted(self._scores.items(), key=self._rank_key)
return [p for p, _ in ranked[page_no * size:(page_no + 1) * size]]
# ---------- after: what was asked for ----------
class Leaderboard:
def __init__(self) -> None:
self._best: dict[str, int] = {}
def submit(self, player: str, score: int) -> None:
self._best[player] = max(score, self._best.get(player, score))
def top(self, k: int) -> list[str]:
return [p for p, _ in sorted(self._best.items(), key=lambda e: (-e[1], e[0]))[:k]]
class NoStore:
def persist(self, player: str, score: int) -> None:
pass
board, heavy = Leaderboard(), SpeculativeLeaderboard(lambda e: (-e[1], e[0]), NoStore())
for player, score in [("ana", 40), ("bo", 75), ("ana", 90), ("cy", 75)]:
board.submit(player, score)
heavy.submit(player, score)
assert board.top(2) == ["ana", "bo"]
assert len(board.top(10)) == 3
assert heavy.page(0, 2) == board.top(2)
print(board.top(3))
function check(ok: boolean, what: string): void {
if (!ok) throw new Error(what);
}
type Entry = [string, number];
// ---------- before: built for requirements nobody stated ----------
interface RankingStrategy { compare(a: Entry, b: Entry): number }
interface ScoreStore { persist(player: string, score: number): void }
class SpeculativeLeaderboard {
private readonly scores = new Map<string, number>();
private readonly listeners: Array<(p: string, s: number) => void> = [];
constructor(private readonly ranking: RankingStrategy, private readonly store: ScoreStore) {}
addListener(fn: (p: string, s: number) => void): void { this.listeners.push(fn); }
submit(player: string, score: number): void {
this.scores.set(player, Math.max(score, this.scores.get(player) ?? score));
this.store.persist(player, score);
this.listeners.forEach((fn) => fn(player, score));
}
page(pageNo: number, size: number): string[] {
return [...this.scores].sort((a, b) => this.ranking.compare(a, b))
.slice(pageNo * size, (pageNo + 1) * size).map(([p]) => p);
}
}
// ---------- after: what was asked for ----------
class Leaderboard {
private readonly best = new Map<string, number>();
submit(player: string, score: number): void {
this.best.set(player, Math.max(score, this.best.get(player) ?? score));
}
top(k: number): string[] {
return [...this.best].sort((a, b) => b[1] - a[1] || a[0].localeCompare(b[0])).slice(0, k).map(([p]) => p);
}
}
const board = new Leaderboard();
const heavy = new SpeculativeLeaderboard(
{ compare: (a, b) => b[1] - a[1] || a[0].localeCompare(b[0]) },
{ persist: () => {} },
);
for (const [p, s] of [["ana", 40], ["bo", 75], ["ana", 90], ["cy", 75]] as Entry[]) {
board.submit(p, s);
heavy.submit(p, s);
}
check(board.top(2).join() === "ana,bo", "best per player, ties by name");
check(board.top(10).length === 3, "k larger than board");
check(heavy.page(0, 2).join() === board.top(2).join(), "same answer, extra interfaces");
console.log(board.top(3));
The speculative version isn't wrong, it's just heavier. Every test now has to supply a ranking strategy and a store. Every reader has to wonder whether listeners are called synchronously, and what happens if persistence throws halfway through a submit. None of those questions was in the requirement.
5.2 YAGNI versus designing for extension
This is the conflict interviewers probe most. The Open/Closed Principle says design so new behaviour can be added without editing existing code. YAGNI says don't build things you don't need yet. Doesn't OCP ask you to anticipate?
The resolution is in what each principle is about:
- YAGNI is about features. Don't build the UPI integration, the pagination or the plug-in loader before someone asks for them.
- Keeping code easy to change is not a feature. Fowler is explicit about this: YAGNI only works if the code is easy to modify, so refactoring, clear names, small classes and tests aren't speculative. They're what lets you defer features.
So the question isn't "should I make this extensible?" It's "how much does it cost to add the seam now versus later, and how sure am I that I'll need it?"
flowchart TD
Q["Could this vary in future?"] --> S{"Has the interviewer or spec said it will?"}
S -->|"Yes"| B["Build the seam now — interface plus one implementation"]
S -->|"No"| C{"Is adding it later expensive or irreversible?"}
C -->|"Yes: public API, data format, persisted schema"| D["Leave a cheap seam, no extra features"]
C -->|"No: internal code, easy to refactor"| E["Write the concrete thing. Refactor when the second case arrives"]
B --> F["Say why out loud"]
D --> F
E --> F
Three situations justify building the seam early:
- The variation is a stated requirement. "We take cards now, and UPI and wallets next quarter." That's not a guess any more.
- Changing later is expensive or irreversible. Public APIs other teams depend on, file formats written to disk, database schemas, wire protocols. Amazon calls these one-way doors. Most internal class structure is a two-way door: you can walk back through it with a refactor.
- The seam costs almost nothing. Accepting a
Clockin a constructor instead of callingnow()is one parameter. It also buys testability today, so it isn't speculative at all. See Designing for Testability.
Here's the first case done right. The interviewer said more payment methods are coming. You add an interface with one implementation, and nothing more: no factory, no registry, no configuration file. When UPI arrives, it's a new class and checkout doesn't change.
import java.util.*;
// The interviewer said: "cards now, UPI and wallets soon". The seam is justified. Nothing else is built.
interface PaymentMethod { String pay(long cents); }
final class CardPayment implements PaymentMethod {
private final String last4;
CardPayment(String last4) { this.last4 = last4; }
public String pay(long cents) { return "card-" + last4 + ":" + cents; }
}
final class Checkout {
private final List<String> receipts = new ArrayList<>();
String complete(long cents, PaymentMethod method) {
if (cents <= 0) throw new IllegalArgumentException("amount must be positive");
String receipt = method.pay(cents);
receipts.add(receipt);
return receipt;
}
int count() { return receipts.size(); }
}
// Later: "add UPI". A new class. Checkout is not opened.
final class UpiPayment implements PaymentMethod {
private final String vpa;
UpiPayment(String vpa) { this.vpa = vpa; }
public String pay(long cents) { return "upi-" + vpa + ":" + cents; }
}
class ExtensionDemo {
static void check(boolean ok, String what) { if (!ok) throw new AssertionError(what); }
public static void main(String[] args) {
Checkout checkout = new Checkout();
check(checkout.complete(999, new CardPayment("4242")).equals("card-4242:999"), "card");
check(checkout.complete(500, new UpiPayment("ana@bank")).equals("upi-ana@bank:500"), "upi");
check(checkout.count() == 2, "both recorded");
System.out.println("UPI added without touching Checkout");
}
}
from typing import Protocol
# The interviewer said: "cards now, UPI and wallets soon". The seam is justified. Nothing else is built.
class PaymentMethod(Protocol):
def pay(self, cents: int) -> str: ...
class CardPayment:
def __init__(self, last4: str) -> None:
self._last4 = last4
def pay(self, cents: int) -> str:
return f"card-{self._last4}:{cents}"
class Checkout:
def __init__(self) -> None:
self._receipts: list[str] = []
def complete(self, cents: int, method: PaymentMethod) -> str:
if cents <= 0:
raise ValueError("amount must be positive")
receipt = method.pay(cents)
self._receipts.append(receipt)
return receipt
def count(self) -> int:
return len(self._receipts)
# Later: "add UPI". A new class. Checkout is not opened.
class UpiPayment:
def __init__(self, vpa: str) -> None:
self._vpa = vpa
def pay(self, cents: int) -> str:
return f"upi-{self._vpa}:{cents}"
checkout = Checkout()
assert checkout.complete(999, CardPayment("4242")) == "card-4242:999"
assert checkout.complete(500, UpiPayment("ana@bank")) == "upi-ana@bank:500"
assert checkout.count() == 2
print("UPI added without touching Checkout")
function check(ok: boolean, what: string): void {
if (!ok) throw new Error(what);
}
// The interviewer said: "cards now, UPI and wallets soon". The seam is justified. Nothing else is built.
interface PaymentMethod { pay(cents: number): string }
class CardPayment implements PaymentMethod {
constructor(private readonly last4: string) {}
pay(cents: number): string { return `card-${this.last4}:${cents}`; }
}
class Checkout {
private readonly receipts: string[] = [];
complete(cents: number, method: PaymentMethod): string {
if (cents <= 0) throw new RangeError("amount must be positive");
const receipt = method.pay(cents);
this.receipts.push(receipt);
return receipt;
}
count(): number { return this.receipts.length; }
}
// Later: "add UPI". A new class. Checkout is not opened.
class UpiPayment implements PaymentMethod {
constructor(private readonly vpa: string) {}
pay(cents: number): string { return `upi-${this.vpa}:${cents}`; }
}
const checkout = new Checkout();
check(checkout.complete(999, new CardPayment("4242")) === "card-4242:999", "card");
check(checkout.complete(500, new UpiPayment("ana@bank")) === "upi-ana@bank:500", "upi");
check(checkout.count() === 2, "both recorded");
console.log("UPI added without touching Checkout");
Compare this with the leaderboard. Both have an interface. The difference is the evidence: the payment interface answers a stated requirement, and the leaderboard's interfaces answer imagined ones. This is the Strategy pattern at its smallest, and it's the right size for a 45-minute round.
6. When the principles conflict
They do conflict, regularly. Here are the common collisions and how to resolve them.
| Conflict | What it looks like | How to decide |
|---|---|---|
| DRY vs KISS | Removing duplication means adding a base class, a generic helper or a callback parameter | If the extraction needs flags or a callback for the varying part, the duplication is probably cheaper. If it's a clean "same rule, same inputs" extraction, DRY wins |
| DRY vs YAGNI | You extract a general abstraction from two cases "because a third will come" | Wait for the third case (rule of three) unless the two cases are the same business rule |
| YAGNI vs OCP | OCP wants a seam, YAGNI says no one asked | Build the seam if the variation is stated or the change would be expensive later. Otherwise write concrete code and refactor when the variation arrives |
| KISS vs SRP | One clear 25-line method versus five single-purpose classes | Split when the pieces change for different reasons or need testing separately. Don't split a cohesive algorithm just to make classes small |
| KISS vs DRY across modules | Two services both format money. Share a library, or let each own a copy? | Within one module, share. Across independently deployed teams, a little duplication is often cheaper than a shared dependency that couples their release cycles |
| YAGNI vs testability | Injecting a clock "isn't needed" | It is needed: the tests need it today. Testability isn't speculative |
A few rules of thumb fall out of the table:
- Duplication is a debt you can pay later. A wrong abstraction is a debt that grows. Copies are easy to merge once you understand them. A shared abstraction with many callers is hard to split.
- Prefer reversible decisions. When unsure, choose the option that's cheaper to undo. Usually that means less abstraction now.
- Count the concepts, not the lines. KISS is measured in ideas a reader must hold, not characters.
- Let the requirements decide what varies. The interviewer's words are evidence. Your imagination isn't.
War Story (illustrative)
A team built a "universal export framework" for one CSV report: pluggable formatters, a column-mapping DSL and a scheduler hook. Over two years it gained eleven configuration flags as each new report needed something slightly different. When a regulator asked for a fixed-width text file, nobody could add it without breaking an existing report. The fix was to delete the framework, give each report its own small exporter, and extract one shared helper for date formatting. The new code was about a third of the old size, and the next report took an afternoon.
7. When each principle goes too far
| Over-applied | Symptoms | Correction |
|---|---|---|
| DRY | Boolean flags, mode parameters, Utils classes that half the codebase imports, a "base" class whose subclasses override most of it, unrelated modules coupled through a shared helper | Inline the abstraction, delete unused branches, re-extract only what's truly the same knowledge |
| KISS | A 300-line function "because classes are complexity", primitives everywhere instead of value objects, refusing a pattern the requirement plainly needs | Remember that simple means not tangled. Small named pieces are often simpler than one big piece |
| YAGNI | Hard-coded values that are obviously config, no seam where the interviewer named a variation, static calls to the clock, untestable code "because tests aren't a feature" | YAGNI applies to features. Seams, tests and clean structure aren't features |
There's a mirror image to each. Under-applied DRY gives copy-paste drift. Under-applied KISS gives frameworks. Under-applied YAGNI gives plug-in systems with one plug-in. The skill is noticing which way you lean. Most engineers lean one way consistently, so knowing your own bias is half the battle.
8. How this shows up in LLD interviews
Interviewers rarely ask "what is DRY?" They watch for these principles in your design and push on them with follow-ups.
Where it shows up:
- Opening design. If you start with abstract base classes, factories and a plug-in registry before writing a single concrete flow, that's a YAGNI flag. Start with the concrete happy path, then add seams where the requirements say things vary. See the LLD interview framework.
- Extension questions. "Now add a new vehicle type" or "Now support a new payment method" tests whether your design accommodates change. If the change touches six files, you under-designed. If you'd already built for ten variations nobody asked for, you over-designed.
- Code review moments. In machine coding rounds, duplicated pricing or validation logic across classes is easy to spot and costs points. So is a 15-line generic helper used once.
- Defending choices. "Why is this an interface?" is a YAGNI probe. Have an answer tied to a requirement ("you said more methods are coming"), or be ready to say "fair, it doesn't need to be. I'll make it concrete."
Phrases that show judgment:
- "These two checks look the same today, but they're different rules. I'll keep them separate so they can diverge."
- "This is the same discount rule in both places, so it gets one home."
- "I'm not adding a strategy here yet because there's only one algorithm. If you want a second, it's a small refactor: extract the interface and inject it."
- "You mentioned UPI is coming, so I'll put payment behind an interface now. I'm not building a factory or registry. That's for when we have several."
Red flags interviewers note:
- A
UtilsorHelperclass with unrelated static methods. - Interfaces with one implementation and no stated reason.
- The same business rule in two classes.
- Flags on constructors or methods (
new Notifier(true, false)). - Inability to explain why an abstraction exists.
The Common LLD Mistakes page covers over-patterning in more detail, with a vending-machine example.
9. A short checklist
Before you extract shared code:
- Is it the same knowledge, or does it just look alike?
- Can I name the shared concept specifically?
- Will the extraction need flags or callbacks for the varying parts?
- Do I have three real cases, or am I guessing from two?
Before you add an abstraction:
- Which requirement asks for this variation?
- Is it expensive to add later (public API, data format, schema)?
- Is the seam nearly free and useful today (testability)?
- Can I explain it in one sentence?
Before you call something simple:
- How many concepts must a reader hold to change it?
- Are unrelated concerns tangled together?
- Could a teammate change it safely without asking me?
10. Interview questions
-
"What does DRY actually mean?" Each piece of knowledge has one authoritative representation. It's about business rules and decisions, not identical text. Two identical lines can be fine, and two different-looking functions can violate DRY if they encode the same rule.
-
"You have two methods with nearly identical code. Do you merge them?" Ask whether they'd always change together. If they're the same rule, yes. If they coincide by accident, such as two validations that happen to share limits today, keep them apart. If unsure, wait for a third case, and avoid any merge that needs a flag parameter.
-
"What's the wrong abstraction, and how do you fix it?" A shared function or base class that callers keep bending with parameters and conditionals until it serves none of them well. The fix is counter-intuitive: inline it back into its callers, delete each caller's unused branches, and look again for real duplication.
-
"Doesn't YAGNI contradict the Open/Closed Principle?" No. YAGNI is about not building features early. OCP is about structuring code so that adding a feature doesn't mean editing stable code. Build a seam when the variation is stated or the later change would be expensive. Otherwise keep code clean and refactor when the variation shows up.
-
"Isn't adding a
Clockparameter a YAGNI violation?" No. You need it today for deterministic tests, it costs one parameter, and it doesn't add a feature. YAGNI targets speculative functionality, not the structure that makes code testable and changeable. -
"What's the difference between simple and easy?" Simple is about structure: few concerns tangled together. Easy is about familiarity: what's quick for you right now. A clever one-liner can be easy to write and far from simple. Several small single-purpose classes can be simpler than one long method.
-
"Your interviewer says 'make it extensible'. How far do you go?" Ask "extensible in which direction?" Then add a seam for that variation, typically one interface with one implementation, and stop. Show the extension by sketching the second implementation. Don't add factories, registries or config unless they solve a stated problem.
-
"Two microservices both need to format currency. Shared library or duplicate?" Within one codebase, share it. Across independently deployed services owned by different teams, a small duplicated function is often cheaper than a shared library that couples their releases. Revisit if the logic grows or becomes regulatory, where divergence is a real risk.
-
"When would you deliberately duplicate code?" When the two copies represent different knowledge, when the shared version would need flags, across service or team boundaries, and in tests, where readability of each test beats removing repetition.
-
"How do you recognise over-engineering in your own design?" Count the concepts against the requirements. Interfaces with one implementation and no reason, generic names, configuration nobody asked for, and difficulty explaining a component in one sentence are all signs. In an interview, offer to simplify rather than defend it.