Programming Search⌘K

Patterncore

Dead code

Also called dead code, unreachable code, unused code.

A code smell: the source has functions that nobody calls, branches that cannot run and values that nobody reads, and each reader must still read them and keep them working.

Family
code-smell
Intent
Find the code that the program never runs or whose result it never uses, make sure of it with tools and tests, and delete it, so that the source says only what the program does.
Also called
Unreachable code, Unused code
Refactorings
Remove dead code

Intent

Find the code that is in the source but does no work: functions and classes that nothing calls, branches whose condition is never true, statements after a return, and values that are computed and never read. Check with the compiler, a linter and coverage that the code is in fact dead, then delete it. The version control system keeps it, if it is ever needed again.

Problem

The term has two meanings. Wikipedia notes that some use dead code for code "which can never be executed at run-time", and that in other areas it is code "which is executed but whose result is never used in any other computation."1 Code of the first kind is also called unreachable code: code that "can never be executed because there exists no control flow path to the code from the rest of the program."2 For a reader, both kinds cost the same: lines to read, understand and keep working, that change nothing in what the program does.

The forces are these:

  • Dead code looks live. A function with a good name and tests looks like part of the program. Wikipedia notes that "Test scaffolding can make it appear that the code is still live".1 A reader who changes a rule must decide whether the dead copy needs the change too.
  • Code dies quietly. A feature is removed but its helper stays. A branch handles a case that a check further up now rejects. A flag is always set the same way. No one decides to keep the code; no one notices that it died.
  • Fear keeps it. Programmers keep code in case it is needed again, or comment it out. The second edition of Refactoring answers this with version control: once the code is deleted, the history still has it.3
  • Removal can change behaviour. Code whose result is not used can still have an effect. Wikipedia warns that a dead computation "may raise exceptions or affect some global state, thus removal of such code may change the output of the program and introduce unintended bugs."1

Solution

The refactoring is Remove Dead Code, which the catalogue at refactoring.com lists.4

  1. Find candidates. Use the tools that the language gives. Java's compiler refuses some of it: "It is a compile-time error if a statement cannot be executed because it is unreachable".5 Go's compiler refuses an import without a use, because "It is illegal for a package to import itself, directly or indirectly, or to directly import a package without referring to any of its exported identifiers."6 Linters find more: ESLint's rule no-unreachable reports code after return, throw, continue and break,7 and Staticcheck's SA4006 reports "A value assigned to a variable is never read before being overwritten."8
  2. Confirm. Static tools see the source; they cannot see calls by reflection, by name from configuration, or from other programs that use a public API. Coverage helps here. Coverage.py "monitors your program, noting which parts of the code have been executed".9 Code that a full run of the tests and a period in production never executes is a strong candidate.
  3. Delete. Remove the code, its tests and its comments in one commit with a message that says what was removed and why. Do not comment it out.
  4. Run the tests. If they pass and the code was in fact dead, nothing else changes.

Wikipedia notes that detection is a form of control flow analysis, and that "the sophistication of the analysis has a significant impact on the amount of unreachable code that is detected."2 No tool finds all dead code, so the review of a change that removes a feature should also look for the helpers it leaves behind.

Example

A pricing module was written when the shop sold in three currencies. It now sells only in euros, a check at the edge refuses other currencies, and the code for the other two is still there, with a helper that nothing calls and a value that is computed and thrown away.

import assert from "node:assert/strict";

const accepted = new Set(["EUR"]);
function checkCurrency(c) {
  if (!accepted.has(c)) throw new RangeError(`currency ${c} is not accepted`);
  return c;
}

// Before: branches that the edge check makes unreachable, a helper that nothing
// calls, and a value that is computed and never read.
function legacyRoundUsd(cents) {
  return Math.round(cents / 5) * 5;
}
function priceBefore(cents, currency) {
  checkCurrency(currency);
  const withTax = Math.round(cents * 1.2);
  const display = (withTax / 100).toFixed(2); // never read
  if (currency === "USD") return { cents: withTax + 30, currency };
  if (currency === "GBP") return { cents: withTax + 20, currency };
  return { cents: withTax, currency };
  console.log("priced"); // unreachable
}

// After: only the code that runs.
function price(cents, currency) {
  checkCurrency(currency);
  return { cents: Math.round(cents * 1.2), currency };
}

for (const cents of [0, 1, 999, 1250]) {
  assert.deepEqual(price(cents, "EUR"), priceBefore(cents, "EUR"));
}
for (const c of ["USD", "GBP"]) {
  assert.throws(() => priceBefore(100, c), RangeError);
  assert.throws(() => price(100, c), RangeError);
}
assert.equal(typeof legacyRoundUsd, "function"); // still in the source, and no caller
console.log("price: tests pass");
Output
price: tests pass

The second version behaves the same for every input that the edge check lets through, and it fails the same way for the rest. It is shorter, and a reader of it does not wonder whether dollars are still sold.

Language What the example shows
JavaScript unreachable branches, an unused helper and an unread value, removed, as above
Python the same module, and a check with coverage of which lines a test run executes
Java a statement after return that the compiler refuses, and an if (false) that it allows
Go an unused local variable and an unused import, which the compiler refuses, and an unused function, which it allows
PythonGitHub
import sys

ACCEPTED = {"EUR"}


def check_currency(c):
    if c not in ACCEPTED:
        raise ValueError(f"currency {c} is not accepted")
    return c


# Before: unreachable branches, an unused helper and an unread value.
def legacy_round_usd(cents):
    return round(cents / 5) * 5


def price_before(cents, currency):
    check_currency(currency)
    with_tax = round(cents * 1.2)
    display = f"{with_tax / 100:.2f}"  # never read
    if currency == "USD":
        return (with_tax + 30, currency)
    if currency == "GBP":
        return (with_tax + 20, currency)
    return (with_tax, currency)


# After: only the code that runs.
def price(cents, currency):
    check_currency(currency)
    return (round(cents * 1.2), currency)


# A small line tracer, in the spirit of coverage.py: which lines of
# price_before does a run of the tests execute?
code = price_before.__code__
ran = set()


def tracer(frame, event, arg):
    if frame.f_code is code and event == "line":
        ran.add(frame.f_lineno - code.co_firstlineno)
    return tracer


sys.settrace(tracer)
for cents in (0, 1, 999, 1250):
    assert price(cents, "EUR") == price_before(cents, "EUR")
for c in ("USD", "GBP"):
    for f in (price, price_before):
        try:
            f(100, c)
            raise AssertionError("should refuse " + c)
        except ValueError:
            pass
sys.settrace(None)

# Lines 5 and 7, the USD and GBP returns, never ran.
assert 5 not in ran and 7 not in ran and 8 in ran, sorted(ran)
print("price: tests pass")
Output
price: tests pass

The tracer is a small version of what Coverage.py does: it records which lines run. The two return lines for dollars and pounds never run, because check_currency refuses those currencies first. Coverage.py gives the same answer for a whole program, with coverage run and coverage report -m.

JavaGitHub
import java.net.URI;
import java.util.List;
import javax.tools.Diagnostic;
import javax.tools.DiagnosticCollector;
import javax.tools.JavaCompiler;
import javax.tools.JavaFileObject;
import javax.tools.SimpleJavaFileObject;
import javax.tools.ToolProvider;

public class Main {
    static final boolean LEGACY_USD = false;

    // Before: a branch behind a constant that is always false. The compiler
    // allows this form of dead code, on purpose, for conditional compilation.
    static long priceBefore(long cents) {
        long withTax = Math.round(cents * 1.2);
        if (LEGACY_USD) {
            return withTax + 30;
        }
        return withTax;
    }

    // After: only the code that runs.
    static long price(long cents) {
        return Math.round(cents * 1.2);
    }

    // Compile a source string in memory and return the error messages.
    static List<String> errors(String source) {
        JavaCompiler javac = ToolProvider.getSystemJavaCompiler();
        JavaFileObject file = new SimpleJavaFileObject(URI.create("string:///Probe.java"), JavaFileObject.Kind.SOURCE) {
            @Override
            public CharSequence getCharContent(boolean ignoreEncodingErrors) {
                return source;
            }
        };
        DiagnosticCollector<JavaFileObject> diagnostics = new DiagnosticCollector<>();
        javac.getTask(null, null, diagnostics, List.of("-d", System.getProperty("java.io.tmpdir")), null, List.of(file)).call();
        return diagnostics.getDiagnostics().stream()
                .filter(d -> d.getKind() == Diagnostic.Kind.ERROR)
                .map(d -> d.getMessage(null))
                .toList();
    }

    public static void main(String[] args) {
        for (long cents : new long[] {0, 1, 999, 1250}) {
            check(price(cents) == priceBefore(cents), "same price for " + cents);
        }

        // A statement after return is a compile-time error.
        List<String> afterReturn = errors("class Probe { int f() { return 1; System.out.println(); } }");
        check(afterReturn.stream().anyMatch(m -> m.contains("unreachable statement")), "after return: " + afterReturn);

        // A while (false) body is also refused, but if (false) is allowed.
        check(!errors("class Probe { void f() { while (false) { System.out.println(); } } }").isEmpty(), "while false");
        check(errors("class Probe { void f() { if (false) { System.out.println(); } } }").isEmpty(), "if false");
        System.out.println("price: tests pass");
    }

    static void check(boolean ok, String what) {
        if (!ok) {
            throw new AssertionError(what);
        }
    }
}
Output
price: tests pass

The Java Language Specification makes a statement that cannot be reached a compile-time error, and the probe shows javac refusing a statement after return and the body of while (false). The rule for if is different by design: the specification allows if (false) so that a constant flag such as LEGACY_USD can switch code off. That code is dead, and the compiler does not report it, so a linter or a review must.

package main

import (
	"fmt"
	"math"
	"os"
	"os/exec"
	"path/filepath"
	"strings"
)

// Before: a helper that nothing calls. The compiler allows an unused function.
func legacyRoundUSD(cents int) int { return (cents + 2) / 5 * 5 }

func priceBefore(cents int) int {
	withTax := int(math.Round(float64(cents) * 1.2))
	display := fmt.Sprintf("%.2f", float64(withTax)/100)
	_ = display // the blank assignment hides a value that is never read
	return withTax
}

// After: only the code that runs.
func price(cents int) int { return int(math.Round(float64(cents) * 1.2)) }

// vet compiles a small program with the go tool and returns its errors.
func vet(src string) string {
	dir, err := os.MkdirTemp("", "prog-test-dead")
	if err != nil {
		panic(err)
	}
	defer os.RemoveAll(dir)
	file := filepath.Join(dir, "probe.go")
	if err := os.WriteFile(file, []byte(src), 0o600); err != nil {
		panic(err)
	}
	out, _ := exec.Command("go", "vet", file).CombinedOutput()
	return string(out)
}

func main() {
	for _, cents := range []int{0, 1, 999, 1250} {
		if price(cents) != priceBefore(cents) {
			panic("price")
		}
	}

	// An unused local variable and an unused import do not compile.
	local := vet("package main\nfunc main() { x := 1 }\n")
	imp := vet("package main\nimport \"strings\"\nfunc main() {}\n")
	if !strings.Contains(local, "declared and not used") || !strings.Contains(imp, "imported and not used") {
		panic("expected compile errors:\n" + local + imp)
	}
	fmt.Println("price: tests pass")
}
Output
price: tests pass

The Go compiler refuses an unused local variable and an unused import, as the probe shows; the specification allows the first rule and requires the second. It does not refuse an unused function such as legacyRoundUSD, and the blank assignment _ = display silences the rule for display. Those need a linter or a review; Staticcheck is one such linter, and its checks include values that are assigned and never read.

Consequences

The source is shorter and says what the program does. A search for a rule finds only the live copy, and a change does not need to keep dead paths compiling.

Some code looks dead and is not. A public function of a library may have no caller in its own repository, and many outside. A handler may be called by name from configuration, or by reflection. Before deleting, check for these uses, and for a public API, deprecate first.

Removing code that had side effects changes the program, as Wikipedia warns.1 Such code is not dead; it is code whose purpose is hidden. Make the side effect explicit, or confirm that no one needs it, before removing it.

How to fix it

  • A function, class or module that nothing calls: Remove Dead Code, with its tests.4
  • A statement after a return or throw: delete it; the compiler or the linter usually reports it.57
  • A branch that a check elsewhere makes impossible: delete the branch, and keep the check.
  • A value that is computed and never read: delete the computation, after a check that it has no side effect.8
  • Commented-out code: delete it. See Comments.

Speculative Generality. Code written for a need that never came, and that only its tests call, is dead code from the start. See Speculative Generality.

Lazy Element. An element that does almost nothing, as opposed to one that is never used. See Lazy Element.

Detecting smells with tools. Compilers, linters and coverage find most dead code. See Detecting smells with tools.

References

  1. Wikipedia, Dead code, revision 1325383945, the introduction
  2. Wikipedia, Unreachable code, revision 1383170496, the introduction and Analysis
  3. Martin Fowler, with Kent Beck, Refactoring, Improving the Design of Existing Code, second edition, Addison-Wesley, 2018, Chapter 8, Moving Features, Remove Dead Code
  4. Martin Fowler, Catalog of Refactorings, the card Remove Dead Code
  5. The Java Language Specification, Java SE 25 Edition, Chapter 14, 14.22, Unreachable Statements
  6. The Go Programming Language Specification, Variable declarations and Import declarations
  7. ESLint, no-unreachable, the rule summary
  8. Staticcheck, Checks, SA4006
  9. Coverage.py documentation, the introduction

About this page

The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.

LadderLevelWhat the next level needs
Human proofH0 no proof
  • add a proof in proofs/ (06.5)
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW4 complete
  • a review of the text: no review record reviews/YR8CYJ/text.yaml