Techniquecore
Remove dead code
Also called delete dead code.
Delete code that no longer runs or whose results nobody uses, after you check that nothing reaches it; version control keeps the old version if you ever need it.
- Family
- refactoring
- Intent
- Delete code that does nothing, so that readers do not have to work out that it does nothing.
Purpose
Dead code is code that never runs, or that runs but whose result nobody uses. It costs the reader: they must read it, work out that it does nothing, and remember that it does nothing. It also costs the next change, because a search finds it and someone must decide whether to change it too.
Remove dead code deletes it. The catalogue card shows the plainest case, a block guarded by if (false).1 The book's argument against keeping dead code for a possible future need is version control: if the code is needed again, the old revision still has it.2 Commenting code out, in place of deleting it, made sense before version control was common, and the book does not recommend it now.2 See Dead Code for the smell and version control for the history it keeps.
Steps
- If the dead code can be reached from outside, for example a whole function or a public method, search for callers first.2
- Delete the code.
- Test.
Step 1 is where the risk is. A search finds direct calls. It does not find calls through reflection, a name built from a string, a plugin that loads the code at run time, or a client outside the repository.
Example
A pricing module has a branch for a currency that the shop stopped selling in, a helper that nothing calls, and a flag that is always off. After the refactoring, they are gone, and the tests still pass.
import assert from "node:assert/strict";
// Before: three kinds of dead code.
const LEGACY_ROUNDING = false; // a flag that is always off
function legacyRound(c) { return Math.floor(c / 5) * 5; } // only the dead branch calls it
function oldRate(cur) { return cur === "DEM" ? 1.95583 : 1; } // nothing calls it
function priceBefore(cents, cur) {
if (LEGACY_ROUNDING) return legacyRound(cents);
if (cur === "EUR") return cents;
throw new Error(`unsupported currency ${cur}`);
}
// After: only the live code.
function price(cents, cur) {
if (cur === "EUR") return cents;
throw new Error(`unsupported currency ${cur}`);
}
assert.equal(price(1999, "EUR"), priceBefore(1999, "EUR"));
assert.throws(() => price(100, "USD"), /unsupported/);
assert.throws(() => priceBefore(100, "USD"), /unsupported/);
console.log("remove dead code: tests pass");
remove dead code: tests pass
The old helpers are still in the history of the repository. If someone asks why the module has no Deutsche Mark rate, git log -S oldRate finds the commit that removed it.
| Language | What the example shows |
|---|---|
| JavaScript | an always-false flag, a helper only the dead branch calls, and an unused function, removed, as above |
| Python | the same removal, with a note on code that is reached only by name, which a search can miss |
| Go | the same removal; the compiler reports unused imports and local variables, which helps step 1 |
import importlib
# After: only the live code is left.
def price(cents: int, currency: str) -> int:
if currency == "EUR":
return cents
raise ValueError(f"unsupported currency {currency}")
assert price(1999, "EUR") == 1999
try:
price(100, "USD")
raise AssertionError("expected an error")
except ValueError:
pass
# A caller that a text search for "dumps" may miss: the name is built from strings.
def call_by_name(module: str, func: str, *args):
return getattr(importlib.import_module(module), func)(*args)
assert call_by_name("js" + "on", "du" + "mps", [1, 2]) == "[1, 2]"
print("remove dead code: tests pass")
remove dead code: tests pass
package main
import (
"errors"
"fmt"
)
// After: the always-off flag, the helper that only its branch called,
// and the unused rate function are deleted. The compiler would reject
// an unused import or an unused local variable, which leaves fewer
// kinds of dead code to look for by hand.
var errCurrency = errors.New("unsupported currency")
func price(cents int, currency string) (int, error) {
if currency == "EUR" {
return cents, nil
}
return 0, fmt.Errorf("%w %s", errCurrency, currency)
}
func main() {
if c, err := price(1999, "EUR"); err != nil || c != 1999 {
panic("EUR")
}
if _, err := price(100, "USD"); !errors.Is(err, errCurrency) {
panic("USD")
}
fmt.Println("remove dead code: tests pass")
}
remove dead code: tests pass
When to use
- A branch that cannot run. A condition that is always false, or a case for data that no longer exists.
- A function with no callers. After a change, the old version of a function often stays behind.
- Code kept for a future that did not come. That is Speculative Generality.
- Commented-out code. Delete it; version control has it.2
Pitfalls
Callers you cannot see. Public APIs, reflection, dependency injection by name, serialization frameworks and scripts outside the repository all reach code that a search misses. For a public API, deprecate first, and remove in a later release.
Code that only the tests call. A function that only tests use is dead in the product. Delete the tests with it.
Feature flags. Code behind a flag that is off is not dead if the flag can be turned on. Find out whether the flag is still in use before you remove the code it guards.
Tools that do it
Tools find candidates; step 1 and the tests decide.
- Python. "Vulture finds unused code in Python programs."3 It gives each finding a confidence value, and its README warns that, because of Python's dynamic nature, it is likely to miss some dead code, and that code called only implicitly may be reported as unused.3
- Go. The
deadcodecommand "reports unreachable functions in Go programs".4 It uses Rapid Type Analysis, starting from the entry points of the main packages, and its-testflag adds the test programs as entry points.4 The language itself helps: the specification makes an import that the package does not use illegal, and lets a compiler reject a local variable that is never used.5 - JavaScript. ESLint's no-unused-vars rule "is aimed at eliminating unused variables, functions, and function parameters".6
For more tools, see smell detection tools.
References
- Martin Fowler, Catalog of Refactorings, Remove Dead Code, the entry
- Martin Fowler, Refactoring, Improving the Design of Existing Code, second edition, Addison-Wesley, 2018, Chapter 8, Moving Features, Remove Dead Code, motivation and mechanics
- Vulture, README, the introduction; confidence values
- Alan Donovan, Finding unreachable functions with deadcode, The Go Blog, 12 December 2023, the introduction; Rapid Type Analysis; Tests
- The Go Programming Language Specification, Import declarations; Variable declarations, implementation restriction
- ESLint, no-unused-vars, Rule Details
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.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H0 no proof |
|
| Lean | L0 no Lean part |
|
| Visual | V0 none |
|
| Writing | W4 complete |
|
Tag H8PMMW Edit this page History Report an error Markdown