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.
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.
"Shotgun surgery is the smell you feel rather than see: a single business change, say adding Afterpay as a payment method, means touching the
PaymentMethodenum, threeswitchstatements, 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.csandReceiptTemplate.cshtmlchange 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."
| 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 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 |
| 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 |
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.
Checks that the candidate can recognise change-preventer smells, find them with evidence (including git history), and fix them without over-abstracting.
Green flags
Red flags
Common project as the solutionCoupling 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
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.
.editorconfig.IEnumerable<IPaymentMethod>).OrderPlaced published in-process (or via outbox) so Shipping reacts without Order knowing about it.Every interface and event adds indirection. Introduce abstractions at seams where change coupling has been observed, not everywhere just in case.
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);
}
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.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 |
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.
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.
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.
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.
Last updated 23 Nov 2026.