# Dead CodeA new developer spends an afternoon fixing a coupon method nobody has called in two years. Learn to find dead code, delete it, and know when to check first.

A new developer joins the delivery team and gets her first ticket: the legacy coupon rounds the wrong
way. She finds the method, spends the whole afternoon fixing it, and even writes a test. Then the
reviewer asks one question: who calls this? Nobody. Nobody has called it in over two years. That's the
smell called **Dead Code**.

This lesson picks up where [Speculative Generality](/code-smells/speculative-generality/) ends:
the same food-delivery app, one class further along.

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="j2hvDun3K-4" title="Dead Code" >}}

## The afternoon fix

Here is the method she fixed:

```java
Money applyLegacyCoupon(Order order) {
    return order.subtotal().times(0.9);
}
```

An afternoon of careful work, on code that never runs. And it wasn't alone. The checkout code also
holds:

- a `DRONE` case that can never run,
- a block of commented-out code,
- a field nobody reads,
- a private helper nobody calls.

All of it compiles, and all of it looks alive.

## A building directory

Picture the directory in the lobby of an office building. It lists every company, floor by floor. But
two of those companies moved out years ago, and nobody updated the board. So visitors ride the lift up,
walk down the corridor, and knock on an empty office.

Dead code is that stale entry. It looks like a real part of the building, so people keep visiting it.
The course's [Code Smells Reference](https://refactoring-assistant.github.io/dispensables/dead-code)
defines it as any method, line, field or variable that is never used, or can never be reached.

```mermaid {alt="The directory mapped onto the code: a company that moved out is a method nobody calls; the stale board entry is the method still in the file; a visitor knocking on an empty office is a developer reading and fixing code that never runs." caption="The directory, mapped onto the code."}
flowchart LR
  A["company moved out"] --> A2["method nobody calls"]
  B["stale board entry"] --> B2["still in the file"]
  C["visitor knocks"] --> C2["developer reads and fixes it"]
  class A,B,C muted
  class A2,B2,C2 bad
```

## What it looks like

Here is the checkout class. The `total` method is the one thing the app really uses:

```java
class Checkout {
    private LocalDateTime lastSync;
    private final FeeCalculator fees = new FeeCalculator();

    Money total(Order order) {
        Money fee = fees.deliveryFee(order);
        // Money coupon = applyLegacyCoupon(order);
        // return order.subtotal().plus(fee).minus(coupon);
        return order.subtotal().plus(fee);
    }

    Money applyLegacyCoupon(Order order) {
        return order.subtotal().times(0.9);
    }
}
```

Look at the rest. A field called `lastSync`, which nothing reads. A commented-out block, kept in case we
need it. And `applyLegacyCoupon`, a method that nothing calls. Each of these once felt too risky to
delete.

The fee calculator has more:

```java
class FeeCalculator {
    Money deliveryFee(Order order) {
        switch (order.mode()) {
            case DRONE:
                return Money.of(5);
            default:
                return Money.of(3);
        }
    }

    private double roundToQuarter(double amount) {
        return Math.round(amount * 4) / 4.0;
    }
}
```

A delivery fee switch with a `DRONE` case, but nothing ever creates a drone order. And a private helper,
`roundToQuarter`, that nobody calls. No line is wrong. That is what makes it hard to see.

## Why it hurts

**People read it, and trust it.** Dead code looks alive, so it gets studied, tested and even fixed, as
our new developer found out.

**It taxes every change.** Rename a type and you update the dead code too, to keep the build green.

**It rots.** Nobody runs it and nobody tests it. If you ever do call it, you are trusting code that
has not run in years.

And all of it hides the code that matters.

```mermaid {alt="Rename Order: the live caller must be updated, and so must the dead caller, even though nothing runs it. The dead code taxes the change." caption="A change has to update dead code too."}
flowchart LR
  R["rename Order"] --> L["live caller"]
  R --> D["dead caller"]
  class R warn
  class L good
  class D bad
```

## How to find it

1. **Your editor.** Unused warnings, grayed-out members, and Find Usages. Private members are
   the easy case: if nothing in the class calls one, your editor says so. Public ones are harder,
   because a caller can be anywhere, so search the whole project.
2. **A coverage report.** Lines that never run in your tests, or in production, are suspects. The
   `DRONE` case shows up red. (Coverage tools such as JaCoCo mark lines that never executed.)
3. **The compiler, a little.** In Java, a statement that can never be executed does not compile:
   [section 14.22 of the language specification](https://docs.oracle.com/javase/specs/jls/se17/html/jls-14.html#jls-14.22)
   makes unreachable statements a compile-time error. A statement after a `return` is the classic
   case. But the rules look at the structure of the code, not at the data, so a branch no input ever
   reaches (like the `DRONE` case) compiles happily. The specification even allows `if (false)` on
   purpose, for conditional compilation.
4. **Combine the signals.** No callers, no coverage, and a history nobody touches: that is dead.

```mermaid {alt="Four signals for dead code: the editor (unused warnings, Find Usages), a coverage report (lines that never run), the compiler (statically unreachable statements) and the version history (nobody touches it). Combine them: no callers, no coverage, no recent edits means dead." caption="No single signal is enough; combine them."}
flowchart TD
  E["editor<br/>unused, Find Usages"] --> X{"no callers?"}
  C["coverage report<br/>lines never run"] --> Y{"no coverage?"}
  H["history<br/>nobody touches it"] --> Z{"no recent edits?"}
  X -->|yes| D["dead code"]
  Y -->|yes| D
  Z -->|yes| D
  class D bad
```

## The key insight: delete it

You can delete it, because version control remembers. Every line you remove is still in the history.
You can read it, compare it, and bring it back with one command. Commenting code out protects nothing:
Git already keeps it, and the comment only adds clutter.

> **If nothing calls it, delete it. Git remembers.**

## The fix: delete, step by step

The refactoring is called **Remove Dead Code** in Fowler's [catalog](https://refactoring.com/catalog/removeDeadCode.html),
and the course page lists **Remove Method** for unused methods. Let's clean the checkout class.

**The coupon method.** First check: Find Usages says none, and nothing loads it by name. Then delete it.
Delete the commented-out block and the field nobody reads too. The history has them.

```java
class Checkout {
    private final FeeCalculator fees = new FeeCalculator();

    Money total(Order order) {
        Money fee = fees.deliveryFee(order);
        return order.subtotal().plus(fee);
    }
}
```

**The private helper.** `roundToQuarter` has no callers, so it goes as well.

**The `DRONE` case.** It can never run, so remove it. The switch is left with a single branch, so it
collapses:

```java
class FeeCalculator {
    Money deliveryFee(Order order) {
        return Money.of(3);
    }
}
```

**The unused parameter.** Now `deliveryFee` ignores its `order`. **Remove Parameter** drops it. In
Fowler's catalog that lives under [Change Function Declaration](https://refactoring.com/catalog/changeFunctionDeclaration.html).

```java
class FeeCalculator {
    Money deliveryFee() {
        return Money.of(3);
    }
}
```

The caller changes with it:

```java
class Checkout {
    private final FeeCalculator fees = new FeeCalculator();

    Money total(Order order) {
        return order.subtotal().plus(fees.deliveryFee());
    }
}
```

Here is the class now: short, honest, and everything in it is used.

```mermaid {alt="Before and after. Before: Checkout holds lastSync, a commented-out block and applyLegacyCoupon; FeeCalculator holds a DRONE case and roundToQuarter. After: Checkout has only total and FeeCalculator has only deliveryFee." caption="Before: five dead things. After: two live methods."}
flowchart LR
  subgraph before["Before"]
    direction TB
    B1["Checkout<br/>lastSync<br/>commented-out block<br/>applyLegacyCoupon()"]
    B2["FeeCalculator<br/>case DRONE<br/>roundToQuarter()"]
  end
  subgraph after["After"]
    direction TB
    A1["Checkout<br/>total()"]
    A2["FeeCalculator<br/>deliveryFee()"]
    A1 --> A2
  end
  before ~~~ after
  class B1,B2 bad
  class A1,A2 good
```

```mermaid {alt="Class diagram after the cleanup: Checkout has a FeeCalculator and total(Order); FeeCalculator has deliveryFee()." caption="The cleaned-up design."}
classDiagram
  class Checkout {
    -FeeCalculator fees
    total(Order order) Money
  }
  class FeeCalculator {
    deliveryFee() Money
  }
  Checkout --> FeeCalculator : deliveryFee
```

## A second example: the replaced method

Someone wrote a better method, `distanceKm`, but left the old one in place:

```java
class Geo {
    double distanceKm(Point a, Point b) {
        return a.distanceTo(b);
    }

    double calculateDistance(Point a, Point b) {
        double dx = degToRad(b.lon() - a.lon());
        double dy = degToRad(b.lat() - a.lat());
        return Math.sqrt(dx * dx + dy * dy) * 6371;
    }

    private double degToRad(double degrees) {
        return degrees * Math.PI / 180;
    }
}
```

Nobody calls `calculateDistance` anymore. And its helper, `degToRad`, was only ever used by that old
method (the course page uses this same shape as its example). Delete the old method, and the helper
becomes dead too. Delete that as well:

```java
class Geo {
    double distanceKm(Point a, Point b) {
        return a.distanceTo(b);
    }
}
```

Dead code travels in chains. After each deletion, ask what it was the only caller of.

## Commonly confused: speculative generality and duplicate code

[Speculative Generality](/code-smells/speculative-generality/) is dead code's close partner. Both
are code nobody uses. The difference is the story: speculative code was never used at all, while dead
code was used once and then stopped. Left alone, speculative code turns into dead code.

[Duplicate Code](/code-smells/duplicate-code/) is the other neighbor. When a new method replaces
an old one and the old one stays, you have two copies of one job: `calculateDistance` and `distanceKm`.

```mermaid {alt="Two lanes on a timeline ending at today. Speculative generality: never used, dashed all the way. Dead code: used once, solid, then unused, dashed. Left alone, speculative code becomes dead code." caption="Never used, versus used once."}
flowchart TD
  subgraph s["Speculative generality"]
    direction LR
    S1["written for a guess"] --> S2["never used"]
  end
  subgraph d["Dead code"]
    direction LR
    D1["used"] --> D2["stopped being used"]
  end
  S2 -.->|"left alone"| D2
  class S1,S2 warn
  class D1 good
  class D2 bad
```

## A common objection: keep it, we might need it later

Here is the usual objection. But if you do need it, Git has it. Search the history for the method name
(for example `git log -S applyLegacyCoupon`) and bring it back.

And the copy you kept has a problem. Nobody tests it and nobody updates it. After a year of changes
around it, it may not even be correct.

A commented-out block is worse. Tools cannot search it, test it or refactor it. It only sits in the way.

## When to check first

Pause when code only *looks* unused:

- **Reflection** can call a method by its name, and Find Usages will not see it.
- **Serialization and framework callbacks** work the same way. A getter that a JSON library reads has
  no visible caller.
- **A public method may be called from another repository.** Search across your organization before you
  delete it.

In those cases, check first, and leave a note or a test that says why the code exists. But
commented-out code is never one of them. Delete it.

```mermaid {alt="Can I delete this? If it is commented-out code, delete it. If something might call it by reflection, serialization, a framework callback or another repository, check first and document why it exists. If find usages, coverage and history all agree it is unused, delete it." caption="Delete what is truly unused; check what only looks unused."}
flowchart TD
  A{"commented-out<br/>code?"} -->|yes| X["delete it"]
  A -->|no| B{"might reflection, a framework,<br/>serialization or another repo call it?"}
  B -->|yes| C["check first, then keep it<br/>with a note or a test"]
  B -->|no| D{"no callers, no coverage,<br/>no recent edits?"}
  D -->|yes| X
  D -->|no| E["keep it for now, look again"]
  class X bad
  class C warn
  class E muted
```

## Recap

Dead code is code that is never used, or can never be reached. Find it with your editor, a coverage
report and the compiler, and combine the signals. Delete it with Remove Dead Code, Remove Method and
Remove Parameter, then ask what it was the only caller of. Check first when reflection, serialization,
frameworks or other repositories might call it.

```mermaid {alt="Recap chain: dead code, find it, delete it, check first." caption="If nothing calls it, delete it. Git remembers."}
flowchart LR
  A["dead code"] --> B["find it"] --> C["delete it"] --> D["check first"]
  class A bad
  class C good
```

Checklist before you open a pull request:

- Does Find Usages show callers for the method, or only tests?
- Is there commented-out code, an unused field or an unread parameter?
- After deleting one thing, is something else now unused?
- Could reflection, serialization, a framework or another repository call it?

> **If nothing calls it, delete it. Git remembers.**

Related lessons: [Speculative Generality](/code-smells/speculative-generality/) (the partner: code
written for a need that never came becomes dead code) and [Duplicate Code](/code-smells/duplicate-code/)
(an old copy left behind after a rewrite).

## Further reading

- Code Smells Reference: [Dead Code](https://refactoring-assistant.github.io/dispensables/dead-code).
- Refactoring catalog: [Remove Dead Code](https://refactoring.com/catalog/removeDeadCode.html),
  [Change Function Declaration](https://refactoring.com/catalog/changeFunctionDeclaration.html).
- The Java Language Specification, [section 14.22, Unreachable Statements](https://docs.oracle.com/javase/specs/jls/se17/html/jls-14.html#jls-14.22).
