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.
Here’s the trail that one sentence leaves behind:
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.
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.
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).
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.
It isn’t the edits you make. It’s the one you forget.
And even when you remember everything:
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:
| Commit | Price | Shipping | Loyalty | Invoice | Cart |
|---|---|---|---|---|---|
| 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.
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();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.
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.
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.
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.
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.)
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);
}
}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.
Shotgun surgery has a famous mirror image, called Divergent Change.
Customer
class changes when tax rules change, when the email templates change, and when the database
schema changes.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 Surgery | Divergent Change | |
|---|---|---|
| Symptom | one change → edits in many classes | one class → edited for many reasons |
| Example | add Platinum: 4 classes | Customer: tax, email, database |
| Fix direction | consolidate | split |
| Refactorings | Move Method, Move Field, Inline Class | Extract 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.”
Is every multi-file change a smell? No. Some spread is the price of a good structure.
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.
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.
Things that change together belong together. One change, one place.