📁 Sangam Dhakal - Portfolio v2.0 - Netscape Navigator 4.0
_
□
×

📚 Interview question

You find the same discount calculation copy-pasted, with small differences, in three order handlers. Walk me through deciding whether to extract it. How do you tell real duplication from coincidental similarity, and what do you do if an earlier extraction turned out to be the wrong abstraction?

Applies duplication judgment to real code: knowledge versus coincidental duplication, the rule of three, extracting safely under tests, and undoing a wrong abstraction by inlining it back.

Mid-Level Theory Intermediate clean-code code-quality dry duplication refactoring wrong-abstraction

🎯 Key points

  • First ask: is it the same business rule (knowledge) or code that merely looks alike today?
  • Same reason to change and same owner -> real duplication; different stakeholders -> coincidental
  • Classify every difference: customer-visible or money-affecting (needs the product owner's decision), deliberate variation (keep or parameterise), or cosmetic noise (unify freely)
  • Measure the cost: how many places changed for the last few rule changes, and defects caused by copies drifting (git log, incident history)
  • Rule of three: tolerate two copies, extract on the third once the shape is clear
  • Pin all copies with characterisation tests before merging them
  • Wrong abstraction signs: boolean flags and mode parameters added per caller; undo it by inlining back, deleting unused branches, then re-extracting
  • Record the decision (owner of the shared rule, what stays separate) in the PR or an ADR so the team and product owner agree

⏱ 30-second answer

First I'd diff the three copies and ask whether they encode the same business knowledge or just look alike. If finance owns one discount rule and all three must change together when it changes, that's real duplication: pin each copy with tests, decide which differences are bugs, and extract one DiscountPolicy. If they belong to different products with different owners that happen to match today, that's coincidental similarity, and merging them couples things that will drift.

If an earlier extraction has grown boolean flags and if (caller is X) branches, it's the wrong abstraction: inline it back into each caller, delete dead branches, and re-extract only what's genuinely shared. The trade-off: duplication costs edits in several places; the wrong abstraction costs every caller.

🗣 Full answer (senior)

How I would answer this in an interview

"I wouldn't extract on sight. First I'd put the three copies side by side and diff them, because the small differences are the interesting part. Then I'd ask who owns the rule. If it's one discount policy that finance defines and all three handlers must change together when the policy changes, that's duplicated knowledge and it should live in one place. If one is retail pricing, one is a wholesale contract and one is a staff discount, they look alike today but have different owners and will diverge, so merging them creates coupling, not reuse.

When it is real duplication, I do it safely: characterisation tests around each handler first, then I decide for each difference whether it's a bug or a deliberate variation. Bugs get unified, often after checking with the product owner, because a rounding difference in one copy might be what customers are already being charged. Real variations become explicit parameters or a small strategy, not hidden flags. Then I extract with the IDE refactoring and point all three callers at it, one PR at a time.

The mistake I see is the opposite one, sticking with a shared abstraction after it's gone wrong. You can tell because every new caller adds a flag: CalculateDiscount(order, isWholesale, skipLoyalty, useLegacyRounding). At that point the fastest way forward is backwards: inline it into each caller, delete the branches each caller doesn't use, and re-extract the part that's genuinely common. Duplication is far cheaper than the wrong abstraction."


Real vs coincidental duplication

Question Real duplication Coincidental similarity
Same business rule? Yes, one policy No, different rules that match today
Same owner / stakeholder? Yes Different teams or customers
Must change together? Always Rarely or never
Action Extract one implementation Leave separate, maybe name the difference

Decision process

Step What I do
1. Diff Compare copies line by line; list every difference
2. Classify Each difference: bug, deliberate variation, or noise
3. Ask the owner Confirm which behaviour is correct where money is involved
4. Pin Characterisation tests for each caller's current behaviour
5. Extract IDE Extract Method/Class, variations as explicit parameters or strategies
6. Migrate One caller per PR, tests green each time

Signs of a wrong abstraction

Sign Example
Boolean or mode parameters per caller isWholesale, legacyMode
Caller checks inside shared code if (source == OrderSource.Marketplace)
Most callers use a fraction of it Five options, each caller sets one
Fear of changing it Every change needs all teams to review

Production example

In an order platform, a shared PriceCalculator had grown seven boolean parameters across four channels and caused two pricing incidents in a quarter. Inlining it into the four callers removed [~40%] of its branches as dead per channel; the re-extracted common core was 60 lines, and the next channel-specific promotion shipped in [1] day without touching the other channels.

🔍 What the interviewer is checking

Checks that the candidate applies DRY with judgment on real code: telling knowledge duplication from coincidence, merging safely, and recovering from a wrong abstraction.

Green flags

  • Diffs the copies and treats differences as possible bugs or variations
  • Uses owner and reason to change as the test
  • Adds characterisation tests before merging
  • Knows inline-and-re-extract for a wrong abstraction

Red flags

  • Extracts anything that looks similar
  • Adds a flag per caller to shared code
  • Never considers that duplication can be the cheaper option

📚 Learn in depth

1. DRY is about knowledge, not text

The original Pragmatic Programmer definition: "Every piece of knowledge must have a single, unambiguous, authoritative representation within a system." It is about knowledge (a business rule, a schema, a configuration value), not about identical-looking lines. Two identical if statements encoding different rules are not a DRY violation; one rule expressed in a C# class and again in a SQL view is, even though the text differs completely.

2. Why coincidental duplication bites

  Retail discount  ─┐
                     ├─► SharedDiscount()  ◄── change for retail
  Staff discount   ─┘                          breaks staff

Merging code with different reasons to change creates coupling: the two callers can no longer evolve independently. This is the single responsibility principle viewed from the other side.

3. The rule of three

With two copies you often can't see which parts are essential and which are accidental. A third use case reveals the real shape of the abstraction. So tolerate two, extract on three, unless the duplicated thing is a clear, stable business rule (like a GST rate) that should be centralised immediately.

4. How wrong abstractions form

Sandi Metz described the cycle: someone extracts shared code; a new requirement is almost the same, so they add a parameter; repeat. Each step is locally sensible, but the abstraction ends up as a switchboard of flags.

  v1: Calculate(order)
  v2: Calculate(order, isWholesale)
  v3: Calculate(order, isWholesale, skipLoyalty)
  v4: Calculate(order, isWholesale, skipLoyalty, legacyRounding)

The fix is to go backwards: inline, simplify each caller, re-extract.

5. Duplication across boundaries

Across microservices or bounded contexts, a shared library for business logic couples deployments and release cycles. It is often better to duplicate the logic (or the DTO) and let each service own its copy. Share infrastructure (logging, auth plumbing), not domain rules.

Try it yourself

  1. Run a clone detector (SonarQube's duplication metric or Rider's 'Find duplicates') on a repo and classify the top five clones as real or coincidental.
  2. Find a method with two or more boolean parameters and write down what each caller passes; see if the method is really several methods.
  3. Practise the inline-and-re-extract cycle: use the IDE 'Inline Method' refactoring on a shared helper, simplify each caller, then extract again.
  4. Write characterisation tests for two near-duplicate methods with Verify snapshots, then merge them and confirm the snapshots still match.

💻 Code

Three handlers with a copied discount rule, and the extraction once it's confirmed to be one business rule.

// Before: the same loyalty discount copied into three handlers.
public sealed class PlaceWebOrderHandler
{
    public decimal Discount(Order o) =>
        o.Customer.LoyaltyYears >= 3 ? Math.Round(o.Subtotal * 0.05m, 2) : 0m;
}

public sealed class PlacePhoneOrderHandler
{
    public decimal Discount(Order o) =>
        o.Customer.LoyaltyYears >= 3 ? Math.Round(o.Subtotal * 0.05m, 2) : 0m;
}

public sealed class PlaceMarketplaceOrderHandler
{
    // The difference: no loyalty check, so every marketplace order gets 5% off.
    // Bug or deliberate marketplace promotion? Only the product owner can say.
    public decimal Discount(Order o) => Math.Round(o.Subtotal * 0.05m, 2);
}
// After: one policy owned by pricing; the product owner confirmed the missing check was a bug.
// Rounding stays Math.Round's default (MidpointRounding.ToEven) so no customer's discount changes;
// switching to AwayFromZero would be a separate, deliberate behaviour change.
namespace Shop.Pricing;

public sealed class LoyaltyDiscountPolicy
{
    private const int QualifyingYears = 3;
    private const decimal Rate = 0.05m;

    public decimal DiscountFor(Order order) =>
        order.Customer.LoyaltyYears >= QualifyingYears
            ? Math.Round(order.Subtotal * Rate, 2)
            : 0m;
}

public sealed record Customer(int LoyaltyYears);
public sealed record Order(Customer Customer, decimal Subtotal);

// Program.cs
// builder.Services.AddSingleton<LoyaltyDiscountPolicy>();
// A wrong abstraction to recognise and undo: flags per caller.
public decimal CalculateDiscount(Order order, bool isWholesale, bool skipLoyalty, bool legacyRounding)
{
    if (isWholesale) return order.Subtotal * 0.12m;   // only wholesale uses this
    if (skipLoyalty) return 0m;                      // only staff orders
    var d = order.Subtotal * 0.05m;
    return legacyRounding ? Math.Round(d, 2) : Math.Round(d, 2, MidpointRounding.AwayFromZero);
}
// Fix: inline into each caller, delete the branches it never takes, re-extract only LoyaltyDiscountPolicy.

⚠ Common mistakes

  • Mistake: Extracting any code that looks similar. Why it is wrong: coincidental similarity couples code with different reasons to change. Instead: ask whether it's the same business rule with the same owner.
  • Mistake: Judging duplication without its business context. Why it is wrong: two identical-looking retail and staff discount rules belong to different stakeholders and will diverge, while a GST rule written differently in C# and SQL is the same knowledge. Instead: trace each copy back to the rule and the person who owns it.
  • Mistake: Merging copies without diffing them. Why it is wrong: the small differences may be deliberate, or may be what customers are currently charged. Instead: list every difference and classify it before merging.
  • Mistake: Deciding money-affecting differences alone. Why it is wrong: 'fixing' a difference changes what some customers pay. Instead: show the product owner the differences and record the decision.
  • Mistake: Merging without tests. Why it is wrong: you silently change behaviour for at least one caller. Instead: add characterisation tests per caller first.
  • Mistake: Adding a boolean parameter to a shared method for each new caller. Why it is wrong: the abstraction becomes a switchboard that nobody can change safely. Instead: give the new case its own code, or use an explicit strategy.
  • Mistake: Refusing to inline a bad abstraction because "that's adding duplication". Why it is wrong: the wrong abstraction costs more than duplication on every change. Instead: inline, simplify, re-extract.
  • Mistake: Sharing domain logic between microservices through a common NuGet package. Why it is wrong: it couples releases and ownership. Instead: duplicate domain logic per service; share only infrastructure.

🏛 Senior insight: trade-offs

Seniors judge duplication by change, not by text. The useful question is: when this rule changes, how many places must change, and will people know? If the answer is 'three, and nobody will remember', extract. If the answer is 'they change independently', leave them. The rule of three is a good default because two examples rarely reveal which parts vary.

The other senior skill is being willing to go backwards. Inlining a wrong abstraction feels like regression, but it is usually the fastest route to a correct design, and the IDE's Inline Method refactoring makes it safe.

Option When it fits Cost When not to
Extract now Clear, stable rule (tax rate, rounding policy) Small Different owners or reasons to change
Wait for the third copy Shape of the abstraction is unclear Temporary duplication Rule is safety- or money-critical and already diverging
Parameterise One real variation point One parameter Variations keep multiplying
Strategy per variant Several real variants with different rules More types Only one variant exists
Inline and re-extract Abstraction grown flags and caller checks A larger PR or several Abstraction is healthy

🔗 Follow-ups the interviewer may ask

  1. When: Candidate mentions DRY Why: Checks they know DRY is about knowledge, not identical text
    How to answer

    DRY (from The Pragmatic Programmer) says every piece of knowledge should have one authoritative representation in the system. It is about rules, not text: the GST rate, the definition of an overdue invoice or a validation rule should live in one place. Two blocks of code that look the same but change for different reasons are accidental duplication, and merging them couples unrelated features. I remove true duplication of business knowledge quickly, and I tolerate similar-looking code until a real shared concept appears, usually around the third repetition.

  2. When: Candidate says duplication can be acceptable Why: Checks they can defend keeping duplication in a code review
    How to answer

    Duplication is acceptable when the copies are coincidentally similar but represent different knowledge, so they may change independently. Merging them creates the wrong abstraction: a shared helper that gains a flag for each caller. I also accept duplication across bounded contexts and microservices, where a shared model would couple teams and deployments, and in tests, where readable, self-contained cases beat clever shared setup. In review I justify it with three facts: who owns each copy, whether they change for the same reason, and what coupling a shared version would add.

🛠 Real-world problems: how you handle them

A shared price calculator with seven flags
Situation
An order platform at [company] with [four] sales channels sharing one `PriceCalculator`. It had grown [seven] boolean parameters, and pricing changes needed sign-off from every channel team.
Signals
[Two] pricing incidents in a quarter where a change for one channel altered another; PRs to the calculator sat [a week] in review; cyclomatic complexity of [~45] in Sonar.
Investigation
Listed every caller with Find All References and recorded which flags each passed; found each channel used a disjoint subset. Diffed the original copies from git history to see what had been merged; reviewed incident RCAs.
Resolution
Immediately: froze changes to the calculator and added characterisation tests per channel with Verify snapshots. Then: inlined the calculator into each channel, deleted unused branches per channel, and re-extracted a [60]-line shared core (GST and loyalty) with channel-specific promotions in each channel's own code.
Prevention
Review guideline: no new boolean parameter on shared domain code without a design discussion; Sonar quality gate on cognitive complexity for new code; an ADR recording which pricing rules are shared and who owns them.

How to tell it (STAR)

**S:** Our [four] sales channels shared one price calculator that had grown [seven] flags, and changes for one channel kept breaking another. **T:** After the [second] incident I was asked to make pricing safe to change. **A:** I pinned each channel's behaviour with snapshot tests, then inlined the calculator into each channel, removed the branches each one never used, and re-extracted only the genuinely shared GST and loyalty rules, with an ADR naming the owner. **R:** We had [no] cross-channel pricing incidents in the next [two quarters], and a channel promotion that used to take [a week] of reviews shipped in [a day].

More in Clean Code

Last updated 23 Nov 2026.

🌐 Sangam's Webring

⏪ Previous 🏠 Main Next ⏩
💬 Chat with me