# Divergent ChangeOne Invoice class, three teams, three merge conflicts in one sprint. Learn to spot a class with many reasons to change, split it with Extract Class, and know when to leave it.

It's the last week of the sprint, and one file keeps changing: the `Invoice` class. On Monday,
finance changes the tax rule. On Wednesday, design changes the layout of the PDF. On Friday, the
platform team switches the email provider. Three teams, three unrelated reasons, and three merge
conflicts, all in one file. That's a smell called **Divergent Change**: one class, changed for many
unrelated reasons.

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

{{< lesson-video youtube="uzdDtlgGACc" title="Divergent Change" >}}

## One class, three reasons

Here is that sprint as a picture. Nobody edited anything they shouldn't have; the file simply has
three owners.

```mermaid {alt="Three requests in one sprint all edit the same file: finance changes the tax rule on Monday, design changes the PDF layout on Wednesday, and the platform team changes the email provider on Friday. All three arrows end at Invoice.java, which collects three merge conflicts." caption="Three teams, one file."}
flowchart LR
  F["Mon · finance<br/>the tax rule"] --> I["Invoice.java<br/>3 merge conflicts"]
  D["Wed · design<br/>the PDF layout"] --> I
  P["Fri · platform<br/>the email provider"] --> I
  class F c5
  class D c4
  class P c6
  class I bad
```

## The kitchen whiteboard

Picture the whiteboard in a shared kitchen. Everyone in the house writes on it. One housemate works
out who owes how much rent, another keeps the chore rota, and a third keeps the shopping list.
Nobody is doing anything wrong. But every edit smudges the others, and one person's list gets wiped
by accident.

That board is our `Invoice` class. The sections are tax, layout and delivery, and each one belongs
to a different team. Each team is a **reason to change**, and this class has three of them.

```mermaid {alt="The whiteboard mapped onto code. The rent section is the tax calculation owned by finance, the chore rota is the PDF layout owned by design, the shopping list is email delivery owned by platform, and the whole board is the Invoice class." caption="The whiteboard, mapped onto the code."}
flowchart LR
  A["rent split"] --> A2["tax<br/>(finance)"]
  B["chore rota"] --> B2["PDF layout<br/>(design)"]
  C["shopping list"] --> C2["email delivery<br/>(platform)"]
  D["the whole board"] --> D2["the Invoice class"]
  class A2 c5
  class B2 c4
  class C2 c6
  class D2 bad
```

## What it looks like

Here's the invoice class. It holds the lines, the customer's email and the region. Then it does
four jobs: it adds up the subtotal, works out the tax, draws the PDF, and sends the email.

```java
record Invoice(List<Line> lines, String customerEmail,
               String region) {
    double subtotal() {
        return lines.stream().mapToDouble(Line::price).sum();
    }

    double tax() {
        boolean eu = region.equals("EU");
        double rate = eu ? 0.20 : 0.08;
        return subtotal() * rate;
    }

    byte[] toPdf() {
        Pdf pdf = new Pdf();
        pdf.heading("Invoice");
        for (Line l : lines) {
            pdf.row(l.name(), l.price());
        }
        pdf.row("Tax", tax());
        return pdf.bytes();
    }

    void email() {
        byte[] pdf = toPdf();
        MailClient.connect("smtp.acme.test");
        MailClient.send(customerEmail, "Invoice", pdf);
    }
}
```

(`Line` is a small record with a name and a price. `Pdf` and `MailClient` stand for a PDF library
and a mail library; they're placeholders, not real APIs.)

Honestly, that's a natural place to start. An invoice has tax, a layout and a delivery, and the
code reads top to bottom. Everything about invoices is in one place, and for a while that's
convenient.

## Why it hurts

Now the sprint begins. On Monday, finance raises the European tax rate: an edit to the `eu` and
`rate` lines. On Wednesday, design adds a logo to the PDF: an edit inside `toPdf`. On Friday, the
platform team moves to a new mail server: an edit inside `email`. Three edits, three branches, one
file. Each reviewer must read the other two teams' code to be sure nothing broke.

And the parts are tangled. The PDF method calls `tax()`, and the email method calls `toPdf()`. So a
change to the layout can break the tax line. Nobody owns the whole class, and every edit feels
risky.

## How to spot it

- **Unrelated reasons in the history.** If one file's commit messages give unrelated reasons ("fix
  EU tax rate", "new PDF logo", "switch mail provider"), that's the signal. In git, run
  `git log --oneline -- Invoice.java` on that one file and read the messages.
- **Each kind of change touches a different set of methods.** Whenever the layout changes you edit
  these methods; whenever the provider changes you edit those. (Fowler and Beck describe the same
  test: one set of functions you edit for every new database, and a different set for every new
  financial instrument.)
- **Methods use different fields.** Tax reads the region, the PDF reads the lines, the email reads
  the address. The Code Smells Reference lists tightly coupled fields and methods, and methods that
  use another concern's fields, as signs.
- **Its description needs "and".** If you describe the class as "calculates tax **and** draws PDFs
  **and** sends email", there are three classes inside.

## The key insight: group by reason to change

Don't group code by the thing it's about. Group it by the reason it changes. Notice that the noun is
the same in all three jobs: it's always "invoice". Only the reasons differ.

For each method, ask who would request a change to it. If the answers differ, the methods don't
belong together. Think of a reason as a person or a team who can ask for an edit, not as a single
method. Robert Martin's single responsibility principle says the same: a class should have one
reason to change.

> **One class, one reason to change.**

## The fix: Extract Class

The refactoring is called **Extract Class**: take the part that changes for one reason, and give it
its own class. Start with tax. It needs only the region and the subtotal, so the new tax calculator
takes an invoice, and the invoice keeps its lines and its subtotal.

```java
class TaxCalculator {
    double tax(Invoice inv) {
        boolean eu = inv.region().equals("EU");
        double rate = eu ? 0.20 : 0.08;
        return inv.subtotal() * rate;
    }
}
```

```java
record Invoice(List<Line> lines, String customerEmail,
               String region) {
    double subtotal() {
        return lines.stream().mapToDouble(Line::price).sum();
    }
}
```

Next, the layout. The invoice PDF renderer draws the page, and asks the tax calculator for the tax
line.

```java
record InvoicePdfRenderer(TaxCalculator taxes) {
    byte[] render(Invoice inv) {
        Pdf pdf = new Pdf();
        pdf.heading("Invoice");
        for (Line l : inv.lines()) {
            pdf.row(l.name(), l.price());
        }
        pdf.row("Tax", taxes.tax(inv));
        return pdf.bytes();
    }
}
```

Last, delivery. The invoice mailer asks the renderer for the PDF, and sends it.

```java
record InvoiceMailer(InvoicePdfRenderer renderer) {
    void send(Invoice inv) {
        String to = inv.customerEmail();
        byte[] pdf = renderer.render(inv);
        MailClient.connect("smtp.acme.test");
        MailClient.send(to, "Invoice", pdf);
    }
}
```

`Invoice` is now just data and its core behavior. Each other class has one reason to change, and
one team that owns it.

```mermaid {alt="Class diagram after Extract Class. InvoiceMailer uses an InvoicePdfRenderer, which uses a TaxCalculator, which reads an Invoice. Invoice keeps its data and subtotal; each of the other three classes takes an Invoice as input." caption="One class for each reason."}
classDiagram
  direction TB
  class InvoiceMailer {
    send(Invoice)
  }
  class InvoicePdfRenderer {
    render(Invoice)
  }
  class TaxCalculator {
    tax(Invoice)
  }
  class Invoice {
    subtotal()
  }
  InvoiceMailer o--> InvoicePdfRenderer
  InvoicePdfRenderer o--> TaxCalculator
  TaxCalculator ..> Invoice
```

When the concerns run in a sequence, like tax, then layout, then delivery, Fowler also offers
**Split Phase**: separate the steps with a clear data structure between them. When calls go back
and forth between two concerns, he suggests Move Function; when one function mixes both kinds of
work, Extract Function first. For classes, Extract Class is the usual tool. The refactoring.guru
page also lists Extract Superclass and Extract Subclass for classes that share behavior.

## Replay the sprint

Now replay the sprint. On Monday, the tax rule changes, and only the tax calculator is edited. On
Wednesday, the layout changes, and only the renderer is edited. On Friday, the provider changes, and
only the mailer is edited. Three teams, three files, and no conflicts. And you can test the tax rule
without drawing a single PDF.

```mermaid {alt="Before and after Extract Class. Before, finance, design and platform requests all edit one Invoice class. After, each request edits one class: finance edits TaxCalculator, design edits InvoicePdfRenderer, platform edits InvoiceMailer." caption="Before and after."}
flowchart TB
  subgraph Before
    direction LR
    B1["finance"]
    B2["design"]
    B3["platform"]
    B1 --> BI["Invoice"]
    B2 --> BI
    B3 --> BI
  end
  subgraph After
    direction LR
    A1["finance"]
    A2["design"]
    A3["platform"]
    A1 --> AT["TaxCalculator"]
    A2 --> AP["InvoicePdfRenderer"]
    A3 --> AM["InvoiceMailer"]
  end
  Before ~~~ After
  class BI bad
  class AT,AP,AM good
```

There is a price. Three classes mean more files and a few more constructor arguments. That's fine
when each class has its own owner. Name each new class after its reason; if you can't name the
reason, you may have split in the wrong place.

## A second example: a small class

Here's a smaller case. A reminder has a text and a due time, and two methods.

```java
record Reminder(String text, LocalDateTime due) {
    boolean isDue(LocalDateTime now) {
        return !now.isBefore(due);
    }

    void notifyUser() {
        PushService.send("Reminder: " + text);
    }
}
```

`isDue` follows the product rules, like snoozing or quiet hours. `notifyUser` follows the platform:
push messages today, maybe texts tomorrow. That's a tiny class with two reasons to change. So the
size isn't the signal; the reasons are. In the history, it shows up the same way: one commit about
snoozing, another about push messages.

Same move: Extract Class. The reminder keeps its data and its rule, and the reminder notifier sends
the message.

```java
record Reminder(String text, LocalDateTime due) {
    boolean isDue(LocalDateTime now) {
        return !now.isBefore(due);
    }
}

class ReminderNotifier {
    void send(Reminder r) {
        PushService.send("Reminder: " + r.text());
    }
}
```

## Mirror images: Shotgun Surgery

Divergent change has a mirror image: [Shotgun Surgery](/code-smells/shotgun-surgery/). In
divergent change, one class is changed for many reasons. In shotgun surgery, one reason forces
changes in many classes.

```mermaid {alt="Two mirror-image smells side by side. Divergent Change: finance, design and platform requests all arrive at one Invoice class. Shotgun Surgery: one request fans out to PriceCalculator, ShippingService and InvoicePrinter." caption="Many reasons into one class, or one reason across many classes."}
flowchart TB
  subgraph DC["Divergent Change"]
    direction LR
    R1["finance"]
    R2["design"]
    R3["platform"]
    R1 --> C["Invoice"]
    R2 --> C
    R3 --> C
  end
  subgraph SS["Shotgun Surgery"]
    direction LR
    Q["one request"] --> X1["PriceCalculator"]
    Q --> X2["ShippingService"]
    Q --> X3["InvoicePrinter"]
  end
  DC ~~~ SS
  class C bad
  class X1,X2,X3 bad
  class Q hl
```

Back at the whiteboard, divergent change is three housemates editing one board. Shotgun surgery is
one fact, like a housemate moving out, that has to be fixed on every board. The fixes mirror each
other too: divergent change splits a class apart with Extract Class, while shotgun surgery pulls
scattered code together with Move Method and Inline Class.

## Myths, and when to leave it

Two myths to drop.

- **"It's just a large class."** Not quite. [Large Class](/code-smells/large-class/) counts
  size; divergent change counts reasons. A big class can have one reason to change, and the little
  reminder above had two.
- **"Split everything into tiny classes."** No. A class can have many methods and still have one
  reason. Group methods by reason.

So when should you leave it alone?

- **When the reasons always change together.** Splitting would make you edit two classes for one
  change, which is shotgun surgery.
- **When the class is stable.** If nobody edits it, the smell costs you nothing.

Fowler adds that the boundaries often only show up after several changes. So let the history tell
you where to split.

```mermaid {alt="Decision flow. Does the class change for unrelated reasons? If no, leave it. If yes, do those reasons ever change together? If yes, leave it or extract one class for the group. If no, is the class edited often? If no, it can wait. If yes, apply Extract Class, one class for each reason." caption="When to extract."}
flowchart TD
  Q1{"changed for<br/>unrelated reasons?"} -->|no| L["leave it"]
  Q1 -->|yes| Q2{"do the reasons<br/>always change together?"}
  Q2 -->|yes| L
  Q2 -->|no| Q3{"is it edited often?"}
  Q3 -->|no| W["it can wait"]
  Q3 -->|yes| X["Extract Class<br/>one per reason"]
  class X good
  class L,W muted
```

## Recap

Divergent change is one class that keeps changing for unrelated reasons. Spot it in the history, the
teams and the fields. Fix it with Extract Class: one class for each reason. It mirrors shotgun
surgery, and it isn't the same as a large class.

```mermaid {alt="Recap chain: many reasons in one class, spot it in history, teams and fields, then Extract Class." caption="One class, one reason to change."}
flowchart LR
  A["many reasons,<br/>one class"] --> B["spot it: history,<br/>teams, fields"] --> C["Extract Class"]
  class C good
```

Checklist:

- Does one file's history list unrelated reasons?
- Does each kind of change touch a different set of methods or fields?
- Do different teams review or own parts of the same class?
- Could you split it so each class has one reason, and one owner?
- Would the split make one change touch two classes? Then leave it.

> **One class, one reason to change.**

## Further reading

- Code Smells Reference: [Divergent Change](https://refactoring-assistant.github.io/change-preventers/divergent-change).
- Martin Fowler and Kent Beck, *Refactoring* (2nd ed., 2018), chapter 3, "Divergent Change".
- Refactoring catalog: [Extract Class](https://refactoring.com/catalog/extractClass.html),
  [Split Phase](https://refactoring.com/catalog/splitPhase.html),
  [Move Function](https://refactoring.com/catalog/moveFunction.html).
- refactoring.guru: [Divergent Change](https://refactoring.guru/smells/divergent-change).
- Single-responsibility principle (Robert C. Martin):
  [overview](https://en.wikipedia.org/wiki/Single-responsibility_principle).
