# Shotgun SurgeryOne 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.

{{< lesson-video youtube="sXexhsQSE1k" title="Shotgun Surgery" >}}

## One small change, five files

Here's the trail that one sentence leaves behind:

```mermaid {alt="A single request, add a Platinum tier, fans out into an edit in each of five files: PriceCalculator, ShippingService, LoyaltyService, InvoicePrinter and TierNames." caption="One pull of the trigger, many small holes."}
flowchart LR
  R["Add a Platinum tier"] --> P["PriceCalculator.java<br/>+1 edit"]
  R --> S["ShippingService.java<br/>+1 edit"]
  R --> L["LoyaltyService.java<br/>+1 edit"]
  R --> I["InvoicePrinter.java<br/>+1 edit"]
  R --> N["TierNames.java<br/>+1 edit"]
  class R hl
  class P,S,L,I,N bad
```

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:

```java
// 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.

```mermaid {alt="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." caption="One rule, four copies."}
flowchart LR
  K["What does a<br/>GOLD customer get?"] -.-> P["PriceCalculator<br/>10% off"]
  K -.-> S["ShippingService<br/>free shipping"]
  K -.-> L["LoyaltyService<br/>3x points"]
  K -.-> I["InvoicePrinter<br/>a badge"]
  class K hl
  class P c4
  class S c1
  class L c5
  class I c6
```

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](/patterns/state-pattern/), you've seen this shape
before: [adding maintenance mode](/patterns/state-pattern/#the-obvious-way-a-switch-in-every-method)
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:

```java
// 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.

```mermaid {alt="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." caption="The danger is the edit you forget."}
flowchart LR
  R["Add PLATINUM"] --> P["PriceCalculator<br/>edited"]
  R --> L["LoyaltyService<br/>edited"]
  R --> I["InvoicePrinter<br/>edited"]
  R -.-> S["ShippingService<br/>forgotten"]
  S --> B["Platinum customers<br/>pay for shipping"]
  class R hl
  class P,L,I good
  class S warn
  class B bad
```

> **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:

```text
$ 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](https://refactoring.guru/smells/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.

```java
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`):

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

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

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

// InvoicePrinter
String badge = tier.badge();
```

```mermaid {alt="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." caption="Many copies (top) versus a single owner (bottom)."}
flowchart TB
  subgraph BEFORE["Before: the rule is copied"]
    direction LR
    P1["PriceCalculator<br/>GOLD: 0.90"]
    S1["ShippingService<br/>GOLD: free"]
    L1["LoyaltyService<br/>GOLD: x3"]
    I1["InvoicePrinter<br/>GOLD: badge"]
  end
  subgraph AFTER["After: one owner"]
    direction TB
    P2["PriceCalculator"] --> T["Tier<br/>owns every rule"]
    S2["ShippingService"] --> T
    L2["LoyaltyService"] --> T
    I2["InvoicePrinter"] --> T
  end
  BEFORE ~~~ AFTER
  class P1,S1,L1,I1 bad
  class T good
  class P2 c4
  class S2 c1
  class L2 c5
  class I2 c6
```

```mermaid {alt="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."}
classDiagram
  class Tier {
    <<enumeration>>
    STANDARD
    GOLD
    -double priceFactor
    -boolean freeShipping
    -int pointsMultiplier
    -String badge
    +price(double base) double
    +freeShipping() boolean
    +points(int base) int
    +badge() String
  }
  PriceCalculator ..> Tier
  ShippingService ..> Tier
  LoyaltyService ..> Tier
  InvoicePrinter ..> Tier
```

This is the reverse of the move from the [Feature Envy lesson](/code-smells/feature-envy/).
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**:

```java
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.

```mermaid {alt="After the refactoring, adding Platinum changes only the Tier enum, one line. PriceCalculator, ShippingService, LoyaltyService and InvoicePrinter stay unchanged." caption="One change, one place."}
flowchart LR
  R["Add PLATINUM"] --> T["Tier<br/>+1 line"]
  T -.-> P["PriceCalculator<br/>unchanged"]
  T -.-> S["ShippingService<br/>unchanged"]
  T -.-> L["LoyaltyService<br/>unchanged"]
  T -.-> I["InvoicePrinter<br/>unchanged"]
  class R hl
  class T good
  class P,S,L,I muted
```

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:

```java
// 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](/code-smells/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:

```java
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.

```mermaid {alt="Inline Class: TierDiscount, TierShipping and TierPoints, three tiny classes that always change together, are merged into one Tier owner with price, freeShipping and points." caption="Classes that always change together should be one class."}
flowchart LR
  D["TierDiscount<br/>factor()"] --> T["Tier<br/>price()<br/>freeShipping()<br/>points()"]
  S["TierShipping<br/>isFree()"] --> T
  P["TierPoints<br/>multiplier()"] --> T
  class D,S,P bad
  class T good
```

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:

```java
// 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)`:

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

    static String display(LocalDate date) {
        return date.format(DISPLAY);
    }
}
```

```mermaid {alt="OrderPage, InvoicePdf and ReminderEmail all call Dates.display, which owns the single display pattern. Switching to ISO dates is one edit inside Dates." caption="One clock on the wall instead of a watch on every wrist."}
flowchart LR
  O["OrderPage"] --> D["Dates.display()"]
  I["InvoicePdf"] --> D
  R["ReminderEmail"] --> D
  D --> F["DISPLAY pattern<br/>one edit for ISO dates"]
  class O,I,R muted
  class D good
  class F hl
```

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](/code-smells/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.

```mermaid {alt="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." caption="One change, many classes (top) versus one class, many changes (bottom)."}
flowchart TB
  subgraph SS["Shotgun Surgery"]
    direction TB
    C1["one change:<br/>add Platinum"] --> A1["PriceCalculator"]
    C1 --> A2["ShippingService"]
    C1 --> A3["LoyaltyService"]
    C1 --> A4["InvoicePrinter"]
    A1 & A2 & A3 & A4 --> F1["fix: consolidate<br/>Move Method / Field,<br/>Inline Class"]
  end
  subgraph DC["Divergent Change"]
    direction TB
    X1["tax rules"] --> CU["Customer"]
    X2["email templates"] --> CU
    X3["database schema"] --> CU
    CU --> F2["fix: split<br/>Extract Class"]
  end
  SS ~~~ DC
  class C1 hl
  class A1,A2,A3,A4 bad
  class X1 c4
  class X2 c1
  class X3 c6
  class CU c5
  class F1,F2 good
```

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."*

## 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).

```mermaid {alt="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." caption="Spread across layers or boundaries can be deliberate; spread of one rule is the smell."}
flowchart TD
  Q{"One change needs<br/>edits in many places?"} -->|one per layer| L["By design<br/>keep hops few"]
  Q -->|across services/teams| B["Deliberate duplication<br/>can be fine"]
  Q -->|within one codebase| R{"Same rule,<br/>copied?"}
  R -->|yes| S["Shotgun Surgery:<br/>give it a single owner"]
  R -->|just looks alike| K["Leave it<br/>(rule of three)"]
  class L,B,K good
  class S bad
  class Q,R warn
```

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.

```mermaid {alt="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." caption="Things that change together belong together."}
flowchart LR
  A["Spot the trail<br/>search, co-change,<br/>checklists"] --> B["Pick a<br/>single owner"]
  B --> C["Move the copies<br/>Move Method / Field,<br/>Inline Class"]
  C --> D["One change,<br/>one place"]
  class A bad
  class B,C hl
  class D good
```

- **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](/code-smells/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

- Martin Fowler, *Refactoring: Improving the Design of Existing Code* (2nd ed.), chapter 3
  ("Bad Smells in Code": Shotgun Surgery, Divergent Change) and the Move Function, Move Field
  and Inline Class refactorings.
- [Refactoring.Guru: Shotgun Surgery](https://refactoring.guru/smells/shotgun-surgery)
- Related lessons: [Feature Envy](/code-smells/feature-envy/),
  [State Pattern](/patterns/state-pattern/),
  [Strategy Pattern](/patterns/strategy-pattern/).
