Dead Code

November 26, 20268 minutes

A 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 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.

The afternoon fix

Here is the method she fixed:

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 defines it as any method, line, field or variable that is never used, or can never be reached.

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. 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.
The directory, mapped onto the code.

What it looks like

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

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:

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.

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. 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.
A change has to update dead code too.

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 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.
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. 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.
No single signal is enough; combine them.

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, 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.

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:

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.

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

The caller changes with it:

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.

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. 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.
Before: five dead things. After: two live methods.
Class diagram after the cleanup: Checkout has a FeeCalculator and total(Order); FeeCalculator has deliveryFee(). Class diagram after the cleanup: Checkout has a FeeCalculator and total(Order); FeeCalculator has deliveryFee().
The cleaned-up design.

A second example: the replaced method

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

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:

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

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. 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.
Never used, versus used once.

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.

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. 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.
Delete what is truly unused; check what only looks unused.

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.

Recap chain: dead code, find it, delete it, check first. Recap chain: dead code, find it, delete it, check first.
If nothing calls it, delete it. Git remembers.

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 (the partner: code written for a need that never came becomes dead code) and Duplicate Code (an old copy left behind after a rewrite).

Further reading