Shotgun Surgery

November 24, 202610 minutes

One small request, edits in five files. Learn to spot Shotgun Surgery, give each piece of knowledge a single owner, and tell it apart from its mirror image, Divergent Change.

The product manager has a small request: customers love the Gold membership, so let’s add a Platinum tier. One sentence. How hard can it be? You open the price calculator and add a case. Then the shipping service. Then the loyalty points. Then the invoice printer. One pull of the trigger, and small holes everywhere. That’s why this code smell is called Shotgun Surgery.

Prefer to watch? The narrated video covers the same lesson (about 9 minutes). The article follows it section by section, with diagrams and a little extra depth.

One small change, five files

Here’s the trail that one sentence leaves behind:

A single request, add a Platinum tier, fans out into an edit in each of five files: PriceCalculator, ShippingService, LoyaltyService, InvoicePrinter and TierNames. A single request, add a Platinum tier, fans out into an edit in each of five files: PriceCalculator, ShippingService, LoyaltyService, InvoicePrinter and TierNames.
One pull of the trigger, many small holes.

When one change means many small edits in many classes, the code is telling you something. In this lesson we’ll see what it looks like, why it hurts, how to spot it, and how to give each piece of knowledge a single home.

What it looks like

Here’s how the code got that way. Four classes, each with one small line about Gold customers:

// PriceCalculator
if (tier.equals("GOLD")) price = price * 0.90;

// ShippingService
if (tier.equals("GOLD")) return 0.0;

// LoyaltyService
int points = tier.equals("GOLD") ? base * 3 : base;

// InvoicePrinter
String badge = tier.equals("GOLD") ? "Gold member" : "";

Gold customers get ten percent off. Gold customers ship for free. Gold customers earn triple points. And Gold customers get a badge on their invoice.

Each line is tiny and harmless. But together, they’re one piece of knowledge, what a Gold customer gets, copied into four places. It’s like a family recipe copied onto index cards in four different kitchens: change the salt, and you have to update every card.

One piece of knowledge, what a Gold customer gets, is copied into four classes: PriceCalculator holds 10 percent off, ShippingService holds free shipping, LoyaltyService holds triple points, InvoicePrinter holds the badge. One piece of knowledge, what a Gold customer gets, is copied into four classes: PriceCalculator holds 10 percent off, ShippingService holds free shipping, LoyaltyService holds triple points, InvoicePrinter holds the badge.
One rule, four copies.

Martin Fowler describes the smell in Refactoring: “every time you make a change, you have to make a lot of little edits to a lot of different classes.”

If you read the State pattern lesson, you’ve seen this shape before: adding maintenance mode meant a new case in every single method. Same smell, just inside one class (there, the State pattern was the fix, because the scattered knowledge was per-state behavior).

Why it hurts

So let’s add Platinum. The price calculator gets a new line, the loyalty service gets a new branch, and the invoice printer gets a new badge:

// PriceCalculator
if (tier.equals("GOLD")) price = price * 0.90;
if (tier.equals("PLATINUM")) price = price * 0.85;

// LoyaltyService
int points = tier.equals("GOLD") ? base * 3
           : tier.equals("PLATINUM") ? base * 5 : base;

But we forgot the shipping service. Nothing fails to compile. No test goes red. Platinum customers, your very best customers, quietly pay for shipping.

Adding Platinum: PriceCalculator, LoyaltyService and InvoicePrinter were edited, but ShippingService was forgotten, so Platinum customers pay for shipping, with no compile error and no failing test. Adding Platinum: PriceCalculator, LoyaltyService and InvoicePrinter were edited, but ShippingService was forgotten, so Platinum customers pay for shipping, with no compile error and no failing test.
The danger is the edit you forget.

It isn’t the edits you make. It’s the one you forget.

And even when you remember everything:

  • Missed spots. Nothing connects the copies, so nothing reminds you of the last one.
  • Slow changes. Find, edit, review and test four files for a one-sentence request.
  • Merge conflicts. Every tier change touches the same hot files as everyone else’s work.
  • The rule lives nowhere. Nobody can open one file and read what Platinum gets.

How to spot it

How do you spot shotgun surgery before it bites? Look for four signals.

1. Search hits. Search for the same literal or the same condition. If a search for GOLD lights up files all over the project, that’s a trail:

$ grep -rn '"GOLD"' src/
src/pricing/PriceCalculator.java:41:   if (tier.equals("GOLD")) ...
src/shipping/ShippingService.java:27:  if (tier.equals("GOLD")) ...
src/loyalty/LoyaltyService.java:63:    tier.equals("GOLD") ? ...
src/billing/InvoicePrinter.java:88:    tier.equals("GOLD") ? ...

2. Co-change. Check your version history. If the same group of files changes together, commit after commit, they share a secret. (git log --name-only piped through a small script, or code-analysis tools that report change coupling, make this visible.) In this history, the four tier classes (PriceCalculator, ShippingService, LoyaltyService, InvoicePrinter) change in every tier commit, while CartController changes on its own:

CommitPriceShippingLoyaltyInvoiceCart
c1 fix cart total✓
c2 add SILVER✓✓✓✓
c3 cart UI✓
c4 GOLD 12% off✓✓✓✓
c5 cart bug✓
c6 add PLATINUM✓✓✓✓

3. Parallel conditionals. The same switch or if chain on the same type code, in several classes (the Switch Statements smell spread across files).

4. Checklists. A wiki page or a comment that says “when you add a tier, remember to also update these five places.” That checklist is the smell, written down.

Put the signals together, and you get a simple rule of thumb: if files always change together, the knowledge they share wants to live together.

The key insight: give the knowledge a single owner

So what’s the fix? The opposite of scattering: consolidate. Give the knowledge a single owner, one master recipe card that every kitchen reads from.

Here, the owner is a Tier enum. We use Move Field to bring each number into it (the discount, the free shipping flag, the points multiplier, and the badge), and Move Method to bring the behavior with the data: the tier knows how to price, how many points to award, and which badge to show.

enum Tier {
    STANDARD(1.00, false, 1, ""),
    GOLD    (0.90, true,  3, "Gold member");

    private final double priceFactor;
    private final boolean freeShipping;
    private final int pointsMultiplier;
    private final String badge;

    Tier(double priceFactor, boolean freeShipping,
         int pointsMultiplier, String badge) {
        this.priceFactor = priceFactor;
        this.freeShipping = freeShipping;
        this.pointsMultiplier = pointsMultiplier;
        this.badge = badge;
    }

    double price(double base) { return base * priceFactor; }
    boolean freeShipping()    { return freeShipping; }
    int points(int base)      { return base * pointsMultiplier; }
    String badge()            { return badge; }
}

Now the four callers shrink to one-liners. None of them knows what Gold means anymore; they just ask their tier (here tier is a Tier, not a String):

// PriceCalculator
price = tier.price(price);

// ShippingService
if (tier.freeShipping()) return 0.0;

// LoyaltyService
int points = tier.points(base);

// InvoicePrinter
String badge = tier.badge();
Before: the Gold rule is copied inside PriceCalculator, ShippingService, LoyaltyService and InvoicePrinter. After: all four classes ask a single Tier owner, which holds the rule. Before: the Gold rule is copied inside PriceCalculator, ShippingService, LoyaltyService and InvoicePrinter. After: all four classes ask a single Tier owner, which holds the rule.
Many copies (top) versus a single owner (bottom).
Class diagram: enum Tier with STANDARD and GOLD constants, private fields priceFactor, freeShipping, pointsMultiplier and badge, and methods price, freeShipping, points and badge. PriceCalculator, ShippingService, LoyaltyService and InvoicePrinter depend on Tier. Class diagram: enum Tier with STANDARD and GOLD constants, private fields priceFactor, freeShipping, pointsMultiplier and badge, and methods price, freeShipping, points and badge. PriceCalculator, ShippingService, LoyaltyService and InvoicePrinter depend on Tier.

This is the reverse of the move from the Feature Envy lesson. There, one method moved to its data. Here, many copies of a rule move into one place.

Give the knowledge a single owner.

One change, one place

Now the product manager comes back: add Platinum. This time it’s one line, in one file:

enum Tier {
    STANDARD(1.00, false, 1, ""),
    GOLD    (0.90, true,  3, "Gold member"),
    PLATINUM(0.85, true,  5, "Platinum member");

The callers don’t change at all. And because the tier is an enum, the compiler checks every use: a misspelled "PLATNUM" string is no longer possible, and a constructor call missing an argument doesn’t compile. There’s no fourth file to forget.

After the refactoring, adding Platinum changes only the Tier enum, one line. PriceCalculator, ShippingService, LoyaltyService and InvoicePrinter stay unchanged. After the refactoring, adding Platinum changes only the Tier enum, one line. PriceCalculator, ShippingService, LoyaltyService and InvoicePrinter stay unchanged.
One change, one place.

One warning, though. Moving the data isn’t enough. If callers keep asking the tier for numbers and doing the math themselves, that’s feature envy, and the scattering creeps back:

// envy again: the caller does Tier's math
price = price * tier.getPriceFactor();

// behavior stays with the owner
price = tier.price(price);

The two smells are linked in both directions: keeping behavior with its owner prevents consolidation from turning into Feature Envy, and moving envious methods home is exactly how you prevent shotgun surgery in the first place.

One change, one place.

Inline Class: when the pieces are tiny classes

Sometimes the scattered pieces are already classes. Just tiny ones:

class TierDiscount {
    double factor(String t) { return t.equals("GOLD") ? 0.90 : 1.00; }
}

class TierShipping {
    boolean isFree(String t) { return t.equals("GOLD"); }
}

class TierPoints {
    int multiplier(String t) { return t.equals("GOLD") ? 3 : 1; }
}

They look tidy. But every new tier still means editing all three; they always change together. The refactoring here is Inline Class: fold the tiny classes into one owner. It’s like three drawers that each hold one spoon: put the spoons in one drawer.

Inline Class: TierDiscount, TierShipping and TierPoints, three tiny classes that always change together, are merged into one Tier owner with price, freeShipping and points. Inline Class: TierDiscount, TierShipping and TierPoints, three tiny classes that always change together, are merged into one Tier owner with price, freeShipping and points.
Classes that always change together should be one class.

After inlining, the tier enum owns pricing, shipping and points, and a new tier is, once again, a single line. (Too many tiny classes are the other way to scatter knowledge: small is good, but not when every change has to visit all of them.)

A second example: the date format

Here’s an everyday example. The order page shows a date, day, month, year. So does the invoice. So does the reminder email. Each one builds the same formatter:

// OrderPage
String shown = date.format(DateTimeFormatter.ofPattern("dd/MM/yyyy"));

// InvoicePdf
pdf.text(due.format(DateTimeFormatter.ofPattern("dd/MM/yyyy")));

// ReminderEmail
body += when.format(DateTimeFormatter.ofPattern("dd/MM/yyyy"));

Then the company switches to international dates, year first (yyyy-MM-dd), and you go hunting for every copy of that pattern.

Same fix: Extract Method to pull the formatting into a method, then Move Method to one owner, a small Dates class. Every page just calls Dates.display(date):

final class Dates {
    private static final DateTimeFormatter DISPLAY =
        DateTimeFormatter.ofPattern("dd/MM/yyyy");

    static String display(LocalDate date) {
        return date.format(DISPLAY);
    }
}
OrderPage, InvoicePdf and ReminderEmail all call Dates.display, which owns the single display pattern. Switching to ISO dates is one edit inside Dates. OrderPage, InvoicePdf and ReminderEmail all call Dates.display, which owns the single display pattern. Switching to ISO dates is one edit inside Dates.
One clock on the wall instead of a watch on every wrist.

Notice that a shared constant alone wouldn’t be enough. The formatting itself is behavior (which zone? which locale? what about null?), and behavior needs a home too. Now the switch to international dates is one edit.

The classic opposite: Divergent Change

Shotgun surgery has a famous mirror image, called Divergent Change.

  • With shotgun surgery, one change hits many classes. Adding Platinum touched four of them.
  • With divergent change, one class gets hit by many different changes. A Customer class changes when tax rules change, when the email templates change, and when the database schema changes.
Top, Shotgun Surgery: one change, add Platinum, hits PriceCalculator, ShippingService, LoyaltyService and InvoicePrinter; fix by consolidating. Bottom, Divergent Change: three different changes, tax rules, email templates and the database schema, all hit one Customer class; fix by splitting with Extract Class. Top, Shotgun Surgery: one change, add Platinum, hits PriceCalculator, ShippingService, LoyaltyService and InvoicePrinter; fix by consolidating. Bottom, Divergent Change: three different changes, tax rules, email templates and the database schema, all hit one Customer class; fix by splitting with Extract Class.
One change, many classes (top) versus one class, many changes (bottom).

So the fixes point in opposite directions. For shotgun surgery, you consolidate, with Move Method, Move Field and Inline Class. For divergent change, you split, with Extract Class.

Shotgun SurgeryDivergent Change
Symptomone change → edits in many classesone class → edited for many reasons
Exampleadd Platinum: 4 classesCustomer: tax, email, database
Fix directionconsolidatesplit
RefactoringsMove Method, Move Field, Inline ClassExtract Class (and Move Method out)

Both are aiming for the same thing: things that change together belong together. That’s the heart of the Single Responsibility Principle, read as “a class should have one reason to change.”

When it’s acceptable

Is every multi-file change a smell? No. Some spread is the price of a good structure.

  • Layers. Add a phone number to a customer, and it travels through the layers: the database, the domain, the API, and the form. That’s one edit per layer, by design. Keep the hops few, keep related files close together, and generate the boring ones where you can.
  • Boundaries. Across team or service boundaries, a little duplication can be cheaper than a shared dependency. Two services each formatting money their own way can evolve and deploy independently.
  • Too early. Don’t consolidate on the first repeat. Ask whether the copies are really the same knowledge, or just code that happens to look alike (the rule of three is a good default).
Decision flowchart: does one change need edits in many places? If the edits are one per architectural layer, that is by design. If they cross team or service boundaries, duplication may be deliberate. If the copies are the same rule, it is shotgun surgery: give the knowledge a single owner. If they only look alike, leave them. Decision flowchart: does one change need edits in many places? If the edits are one per architectural layer, that is by design. If they cross team or service boundaries, duplication may be deliberate. If the copies are the same rule, it is shotgun surgery: give the knowledge a single owner. If they only look alike, leave them.
Spread across layers or boundaries can be deliberate; spread of one rule is the smell.

So the real test isn’t how many files you touch. It’s whether you’re editing one rule that was copied, or several genuinely different things.

Recap

Shotgun surgery is when one change forces many small edits across many classes. Spot it with searches, version history, parallel conditionals, and checklists. Fix it by giving the knowledge a single owner, with Move Method, Move Field and Inline Class. And remember its mirror image, Divergent Change, which you fix by splitting.

Recap chain: spot the trail with searches, co-change, parallel conditionals and checklists; pick a single owner; move the copies there with Move Method, Move Field or Inline Class; the result is one change, one place. Recap chain: spot the trail with searches, co-change, parallel conditionals and checklists; pick a single owner; move the copies there with Move Method, Move Field or Inline Class; the result is one change, one place.
Things that change together belong together.
  • Shotgun Surgery: one change, many small edits in many classes.
  • It hurts because the edit you forget compiles fine, every change is slow, merges conflict, and the rule lives nowhere.
  • Spot it: search hits, co-change in history, parallel conditionals, “also update…” checklists.
  • Fix it: one owner for the knowledge (Move Field + Move Method), Inline Class for tiny classes that always change together; keep behavior with the owner so it doesn’t turn into Feature Envy.
  • Opposite: Divergent Change, one class changed for many reasons; split it with Extract Class.
  • Leave it when the spread is one edit per layer, crosses deliberate boundaries, or the copies only look alike.

Things that change together belong together. One change, one place.

Further reading