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

📚 Interview question

What are shotgun surgery and tight coupling? How would you find them using your version control history (change coupling) as well as the code, and how do you fix them in a .NET solution?

Explains shotgun surgery, divergent change and tight coupling, how to detect them from git history (files that change together, temporal coupling) and from code (dependency graphs, CA1506), and how to fix them by co-locating behaviour, vertical slices and stable abstractions in .NET.

Mid-Level Theory Intermediate change-coupling code-quality code-smells coupling git shotgun-surgery

🎯 Key points

  • Shotgun surgery: one logical change needs small edits in many classes
  • Divergent change is the related but distinct smell: one class changes for many unrelated reasons; both mean knowledge is in the wrong place
  • Tight coupling: modules depend on each other's concrete types or internals, so changes ripple
  • Static signs in code: new-ing concrete dependencies, static calls into other modules, shared enums switched on everywhere, cyclic references, high CA1506 class coupling
  • Git history shows change (temporal) coupling, including hidden coupling static analysis misses; e.g. files co-changing in >30% of PRs
  • Fix shotgun surgery by moving scattered knowledge into one place (move method/field, polymorphism, vertical slice)
  • Fix tight coupling with dependency inversion only at real seams, events between modules and dependency direction rules
  • Co-change within one feature is normal; co-change across modules or teams is the smell; verify with architecture tests and re-measuring

⏱ 30-second answer

Shotgun surgery is when one logical change, like adding a payment method, needs small edits in ten files across the solution. Tight coupling is the cause: modules depend on each other's concrete types, enums or internals, so changes ripple.

The code shows static coupling (references, CA1506 class coupling). Your git history shows change coupling: files that keep changing in the same commits. That finds hidden coupling too, such as a C# enum and a SQL lookup table that must stay in sync.

The fix is to put knowledge that changes together in one place (move method, a vertical slice, one strategy per payment method) and use stable abstractions or events between modules. The trade-off: some co-change is healthy (a feature's endpoint, handler and test change together); co-change across modules is the smell.

🗣 Full answer (senior)

How I would answer this in an interview

"Shotgun surgery is the smell you feel rather than see: a single business change, say adding Afterpay as a payment method, means touching the PaymentMethod enum, three switch statements, a validator, a mapper, a SQL seed script, the email template and the admin UI. Each edit is small but missing one is a production bug. Divergent change is the mirror image: one class that changes for many unrelated reasons. Both come from tight coupling, where knowledge about one concept is spread across modules that depend on each other's details.

Static analysis only sees part of it. References, CA1506 class coupling and a dependency graph in Visual Studio or NDepend show who calls whom. But the best evidence is version control: if PaymentMethod.cs, RefundCalculator.cs and ReceiptTemplate.cshtml change together in 60% of commits, they are coupled whether or not they reference each other. That is change coupling, sometimes called temporal or logical coupling. For example, at [company] I [ran a co-change analysis over a year of history] and found [an enum, a stored procedure and a front-end constants file] that changed together in [most] payment PRs.

The fix is to move the knowledge into one place. For the payment example, each payment method becomes one class implementing IPaymentMethod, registered in DI, so adding one is one new file plus one registration. Between modules I depend on a small stable interface or publish an event rather than calling into internals, and I enforce dependency direction with architecture tests. The mistake I see is chasing all co-change: in a vertical slice, the endpoint, handler, validator and test should change together, and that is fine. The smell is co-change that crosses module or team boundaries."


The related smells

Smell Shape Typical .NET example
Shotgun surgery One change, many classes New payment method touches enum, 3 switches, mapper, SQL, UI
Divergent change One class, many reasons OrderService changes for tax, shipping and email wording
Tight coupling Concrete dependencies on internals Shipping news up OrderRepository and reads Order fields
Parallel inheritance hierarchies Add a subclass here, must add one there XmlExporter per ReportType subclass

Static versus change coupling

Static coupling Change coupling
Source Code references Git history
Tools CA1506, VS dependency diagrams, NDepend, NetArchTest git log, CodeScene, code-maat
Finds Direct dependencies Hidden ones: config, SQL, front-end constants, copy-paste
Misses Coupling through data, strings, conventions Code that rarely changes

Fixes

Cause Refactoring
Logic for one concept scattered Move method/field into one class; replace switches with polymorphism
Enum mirrored in SQL and front end Single source of truth (generate, or serve from API)
Module calls another's internals Depend on a small interface or publish a domain event
Layered folders split every feature Vertical slice: keep a feature's files together

Production example

After replacing an enum-plus-switches design with one IPaymentMethod class per method, adding a new payment method typically drops from touching about ten files to two (new class and registration), and the escaped-defect rate for payment changes falls because there is no switch left to forget.

🔍 What the interviewer is checking

Checks that the candidate can recognise change-preventer smells, find them with evidence (including git history), and fix them without over-abstracting.

Green flags

  • Defines shotgun surgery and contrasts it with divergent change
  • Knows change/temporal coupling from version control and why it finds hidden coupling
  • Fixes by co-locating knowledge (polymorphism, vertical slices) and enforcing direction with architecture tests
  • Distinguishes healthy co-change within a feature from cross-module coupling

Red flags

  • Only knows "use interfaces" as a fix
  • Proposes a shared Common project as the solution
  • No way of measuring the problem or the result

📚 Learn in depth

1. Coupling and cohesion

Coupling measures how much one module depends on another; cohesion measures how much a module's parts belong together. Shotgun surgery is low cohesion of a concept: the concept's code is spread out. Divergent change is low cohesion of a class: unrelated concepts share a home.

Shotgun surgery                    Divergent change

concept: PaymentMethod            class: OrderService
  -> Enum.cs                        <- tax rule change
  -> Validator.cs                   <- shipping change
  -> RefundCalculator.cs            <- email wording
  -> Mapper.cs                      <- reporting
  -> seed.sql

2. Mining change coupling from git

The idea (popularised by Adam Tornhill's Your Code as a Crime Scene): for every pair of files, count commits that touch both, divided by commits that touch either.

# Files changed per commit over the last year
git log --since="1 year ago" --name-only --format='--%h' > changes.txt

Then group by commit and count pairs (a short script, or code-maat's coupling analysis, or CodeScene). Thresholds that work in practice: at least ~10 shared commits and ~30% coupling degree. Group by PR rather than commit if people commit in small steps.

Caveats: bulk formatting commits and renames create noise (exclude them), and same-PR co-change in a vertical slice is expected.

3. Static coupling tools in .NET

  • CA1506 (class coupling) and CA1502 in .editorconfig.
  • Visual Studio Code Map / dependency diagrams; NDepend for dependency matrices and cycles.
  • NetArchTest or ArchUnitNET to assert rules, e.g. "Billing must not depend on Shipping.Internal".

4. Fix patterns

  • Move method / move field until one class owns the concept.
  • Replace conditional with polymorphism: each variant is a class; DI collects them (IEnumerable<IPaymentMethod>).
  • Vertical slices: organise by feature so code that changes together lives together.
  • Events between modules: OrderPlaced published in-process (or via outbox) so Shipping reacts without Order knowing about it.
  • Single source of truth for shared lists: generate TypeScript constants from C#, or serve lookup data from an API, instead of three hand-maintained copies.

5. Don't over-decouple

Every interface and event adds indirection. Introduce abstractions at seams where change coupling has been observed, not everywhere just in case.

Try it yourself

  1. Run the git command above on a repo you know and find the top 10 co-changing file pairs.
  2. For one pair that doesn't reference each other, work out the hidden coupling.
  3. Write a NetArchTest rule forbidding one module from referencing another's internals and see if it passes.
  4. Count how many files the last "add a new X type" feature touched.

💻 Code

Before and after: adding a payment method used to need edits in many places; now it's one class and one registration.

// Before: knowledge about payment methods scattered (shotgun surgery)
namespace Checkout.Before;

public enum PaymentMethod { Card, PayPal, BankTransfer }

public static class Fees
{
    public static decimal For(PaymentMethod m, decimal amount) => m switch
    {
        PaymentMethod.Card => amount * 0.015m,
        PaymentMethod.PayPal => amount * 0.026m + 0.30m,
        PaymentMethod.BankTransfer => 0m,
        _ => throw new ArgumentOutOfRangeException(nameof(m))
    };
}

public static class Refunds
{
    public static bool CanRefund(PaymentMethod m) => m != PaymentMethod.BankTransfer; // another switch
}
// ...plus a mapper, a receipt template and a SQL seed that all list the methods
// After: one class per payment method owns everything about it
namespace Checkout.After;

public interface IPaymentMethod
{
    string Code { get; }
    decimal Fee(decimal amount);
    bool SupportsRefund { get; }
    Task<PaymentResult> ChargeAsync(Money amount, CancellationToken ct);
}

public sealed record Money(decimal Amount, string Currency);
public sealed record PaymentResult(bool Succeeded, string? Reference);

public sealed class CardPayment(ICardGateway gateway) : IPaymentMethod
{
    public string Code => "card";
    public decimal Fee(decimal amount) => amount * 0.015m;
    public bool SupportsRefund => true;
    public Task<PaymentResult> ChargeAsync(Money amount, CancellationToken ct) => gateway.ChargeAsync(amount, ct);
}

public sealed class PaymentMethods(IEnumerable<IPaymentMethod> methods)
{
    private readonly Dictionary<string, IPaymentMethod> _byCode = methods.ToDictionary(m => m.Code);

    public IPaymentMethod Get(string code) =>
        _byCode.TryGetValue(code, out var m) ? m : throw new KeyNotFoundException($"Unknown payment method '{code}'");

    public IEnumerable<string> Codes => _byCode.Keys; // served to the UI: no second copy of the list
}

public interface ICardGateway { Task<PaymentResult> ChargeAsync(Money amount, CancellationToken ct); }
// Program.cs: adding a method = one class + one line
builder.Services.AddScoped<IPaymentMethod, CardPayment>();
builder.Services.AddScoped<IPaymentMethod, PayPalPayment>();
builder.Services.AddScoped<IPaymentMethod, BankTransferPayment>();
builder.Services.AddScoped<PaymentMethods>();
// Architecture test (NetArchTest) keeping module dependencies one-way
[Fact]
public void Shipping_does_not_depend_on_checkout_internals()
{
    var result = Types.InAssembly(typeof(ShippingModule).Assembly)
        .ShouldNot().HaveDependencyOn("Checkout.Internal")
        .GetResult();
    Assert.True(result.IsSuccessful);
}

⚠ Common mistakes

  • Mistake: Looking only at code references for coupling. Why it is wrong: Coupling through enums mirrored in SQL, string keys and front-end constants is invisible to static analysis. Instead: Mine change coupling from git history as well.
  • Mistake: Treating all co-change as bad. Why it is wrong: Co-change is context-dependent: within a single feature or vertical slice, the endpoint, handler, validator and tests are meant to change together. Instead: Treat co-change as a smell only when it spans modules, bounded contexts, teams or repositories.
  • Mistake: Adding interfaces everywhere to "decouple". Why it is wrong: Dependency inversion without a real seam adds a file, a registration and a jump in every navigation, and hides nothing. Instead: Invert dependencies where a module boundary exists or change coupling has actually been observed; keep concrete classes inside a module.
  • Mistake: Fixing shotgun surgery by adding a shared Constants or Common project. Why it is wrong: Everything now depends on one dumping ground, which becomes the next divergent-change hotspot. Instead: Move knowledge to the class that owns the concept.
  • Mistake: Including bulk formatting or rename commits in the analysis. Why it is wrong: They create false coupling between unrelated files. Instead: Exclude them (e.g. by author, message or size) or analyse by PR.
  • Mistake: Replacing direct calls with events everywhere. Why it is wrong: Flows become hard to follow and debug. Instead: Use events across module boundaries; direct calls within a module.
  • Mistake: Not verifying the fix. Why it is wrong: Coupling creeps back. Instead: Add architecture tests and re-run the change-coupling analysis a few months later.

🏛 Senior insight: trade-offs

The senior move is using history as evidence. "These files are coupled" is an opinion; "these three files changed together in 64% of the last 120 payment PRs, across two teams" is a case you can take to a planning meeting. Change coupling across team boundaries is especially expensive because every change needs coordination, so it is often the strongest argument for moving a module boundary (Conway's law in action).

I also measure the result: files touched per feature of that kind, and escaped defects in that area, before and after.

Option When it fits Cost When not to
Move method/field into one owner Knowledge scattered within one module Low Concept genuinely belongs to several contexts
Polymorphism + DI registration Many switches on the same type code Medium Only one switch, rarely changes
Domain events between modules Module A needs to react to B without knowing it Indirection, eventual consistency if async Inside one module
Generate shared lists (C# to TS/SQL) Same list maintained in several languages Build tooling List changes once a year
Move the module boundary Co-change crosses teams constantly Significant, needs agreement Coupling is rare or cheap

🔗 Follow-ups the interviewer may ask

  1. When: Candidate mentions mining git history Why: Checks that they can combine change frequency and complexity to find hotspots
    How to answer

    Combine change frequency from git history with complexity. Count commits per file (git log --name-only), and measure complexity with code metrics or SonarQube cognitive complexity. Files that are both frequently changed and complex are hotspots; they are where smells slow delivery and cause defects. Tools such as CodeScene automate this, but a spreadsheet of the top 20 files works. Cross-check with the bug tracker and add other debt signals such as duplicated blocks and architecture rule violations. Then weigh it against the roadmap: cold code that a planned feature will soon touch moves up the list, while cold code nobody plans to change can wait in the debt register rather than be ignored for ever.

  2. When: Candidate talks about cohesion or putting things that change together in one place Why: Checks their understanding of cohesion and how to improve it in C#
    How to answer

    Cohesion is how strongly the parts of a module belong together. A highly cohesive class has methods that work on the same data towards one purpose, so a change to that concept happens in one place. Low cohesion shows up as Utils or Manager classes with unrelated methods, fields that only one or two methods use, and classes that change for many different reasons. I improve it by grouping code around domain concepts and features, moving methods to the data they use, and splitting classes whose fields form separate clusters.

  3. When: Candidate proposes replacing switches with one class per variant Why: Checks when polymorphism, a strategy dictionary or a single switch expression is the right choice
    How to answer

    The smell isn't the switch; it's the same switch on the same type code repeated in CalculateTax, DueDate, CanCancel and two more places, so adding a kind means hunting for every one. Replace Conditional with Polymorphism gives each kind its own subclass (or policy object), and each switch arm becomes an override, so a new kind is one new class and the compiler forces every abstract member to be implemented.

    If the data shape is the same for every kind, a dictionary of strategies keyed by the enum keeps one entity class and moves only the varying behaviour out. If there's one switch over a closed set, a switch expression is usually the clearest code you can write.

    The trade-off is the expression problem: polymorphism makes adding kinds cheap and adding operations expensive; switches do the opposite.

🛠 Real-world problems: how you handle them

Every new payment method touched ten files and one was always missed
Situation
A checkout service for [an online retailer], [three] teams contributing. Payment methods were an enum with `switch` statements in fees, refunds, receipts and reporting, plus a SQL seed table and a TypeScript constants file in the front end.
Signals
Adding [Afterpay] took [two] sprints; [two] of the last [three] payment-method changes caused a production defect (a refund path threw `ArgumentOutOfRangeException` for the new method); PRs for payment changes averaged [10+] files across [three] repos.
Investigation
Mined [12] months of git history for co-changing files and found `PaymentMethod.cs`, `Fees.cs`, `Refunds.cs`, the receipt template and `paymentMethods.ts` changing together in [over 60%] of payment PRs. Searched for `switch` on `PaymentMethod` with Rider's structural search ([7] occurrences). Checked logs in Application Insights for the refund exception.
Resolution
Immediate: added the missing branch to the refund `switch` and hot-fixed. Real fix: introduced `IPaymentMethod` with one class per method owning fees, refund support and charging; registered them in DI; served the list of methods to the front end from an endpoint so the TypeScript copy was deleted; seeded the SQL table from the registered classes at deploy time.
Prevention
Architecture test forbidding new `switch` statements on payment method codes outside the `PaymentMethods` module (via a small Roslyn analyser); a contract test checks the front end reads the method list from the API; we re-ran the change-coupling analysis [three] months later.

How to tell it (STAR)

**S:** At [company] adding a payment method meant edits in about ten files across [three] repos, and [two] of the last [three] such changes caused production defects because a `switch` was missed. **T:** I wanted adding a payment method to be safe and quick. **A:** I mined our git history and showed that five files changed together in most payment PRs. I replaced the enum and switches with one `IPaymentMethod` class per method registered in DI, and served the list to the front end from the API so there was one source of truth. **R:** The next payment method took [two days] and touched [two] files, and we've had [no] missed-branch defects since.

More in Code Smells

Last updated 23 Nov 2026.

🌐 Sangam's Webring

⏪ Previous 🏠 Main Next ⏩
💬 Chat with me