Skip to navigation

Claude Code Dead Code: Prove Usage Before Removal

In short: Search references, inspect public entry points and history, then remove code in small steps with tests around callers.

Published 20 min read
On this page

Direct answer

Delete dead code only after you have evidence that nothing uses it, and delete it one unit at a time with tests around the remaining callers. A name search that returns no matches is a clue, not proof. Functions can be reached through dynamic dispatch, reflection, configuration strings, framework conventions, and public entry points that a static search will not surface.

The evidence standard has four parts: a direct-reference check, an indirect-reference check, an entry-point check, and a compatibility check. Require all four before deleting a unit (F051, derived). For anything published, SemVer requires a major increment for an incompatible public API change (F049, official), so removing an exported symbol is a versioning decision, not just a cleanup. Git history from git log, git show, and git describe provides context about when and why the code arrived (F050, official), though history alone does not establish current usage.

Removal shrinks the surface you have to read, test, and maintain. It is worth doing carefully rather than confidently.

Evidence map showing direct references, indirect references, entry-point status, and history as the four checks required before removing a symbol.
Editorial evidence map based on F049 through F051. No search hit is a clue, not proof that nothing calls the code. Not a guarantee that every caller is visible.

Why deleting unused code goes wrong

Unused code is a real cost. It is read by everyone who touches the file, it shows up in search results, it has to be kept compiling, and it suggests behaviors that may no longer be true. Removing it is usually good. Removing the wrong thing breaks production in a way that is hard to diagnose, because the failure appears far from the deletion.

The failure mode is a silent caller. A framework invokes a method by name at runtime. A configuration file names a class as a string. A plugin registry discovers implementations. A public SDK method is called by a consumer you cannot see. In each case, a search for the symbol in your own repository returns nothing, the code looks dead, and deleting it removes behavior that something depends on.

The cost arrives in three shapes. A broken runtime path surfaces weeks later, disconnected from the commit that caused it. A broken public API breaks consumers you do not control and cannot fix. And a batch deletion that removes twenty symbols at once makes it impossible to tell which removal caused a failure, so recovery means restoring all of it.

Static analysis cannot prove non-use in every runtime. That limit is the reason for the four-check standard and for removing one unit at a time. The goal is not to be certain before acting; it is to make each step small enough that a mistake is cheap to find and cheap to undo.

Define what counts as an entry point

Before searching for references, decide what counts as an entry point in your system. An entry point is anything that can invoke code without a visible call site in your source tree.

Entry points differ by language and framework, which is why the list has to be written for your project rather than copied. Common ones include exported module symbols, HTTP route handlers registered by path, message and event handlers registered by topic, methods invoked through reflection or a dependency container, classes instantiated from a configuration string, database-triggered hooks, generated code that references symbols by convention, and anything a published SDK exposes to external consumers.

Entry-point kind How it invokes code Why a search misses it Where to check
Exported public symbol External consumer imports it Consumer is outside the repo Published API surface
HTTP route handler Framework dispatches by path Path is a string, not a symbol Route registration
Message or event handler Broker dispatches by topic Topic is a string Subscription config
Reflection or DI resolution Runtime type lookup Type name is data Container and config files
Config-instantiated class Class name read from settings Name is in a data file Configuration and env
Generated code Generator emits a call by convention Call site does not exist yet Generator templates
Scheduled or triggered job Scheduler invokes by name Name lives in scheduler config Job registration

Write down the entry points that apply to your project and check each one for the symbol under review. This list is the difference between a search and an investigation. The generated-code case deserves its own caution: cleanup of generated output is a different problem from hand-written dead code, and this article does not cover it.

Search direct and indirect references

Start with direct references, then widen to indirect ones. A direct reference is a call or import that names the symbol in source. An indirect reference is one that reaches the symbol through another symbol, a dynamic dispatch, or a data-driven lookup.

For direct references, search the whole repository including tests, build scripts, and configuration. Record what you find. A symbol referenced only by its own definition and its own tests is a candidate. A symbol referenced elsewhere is not dead, whatever the analyzer says.

Symbol Direct references Indirect references Entry-point status Decision
formatLegacyDate Definition only None found Not an entry point Candidate for removal
computeShipping Definition only Reached via ShippingStrategy registry Registered by name Keep; registration is the caller
validateCoupon Definition and two callers None Not an entry point Not dead
renderV1Report Definition and one test Exported from public package Public entry point Compatibility review first

The computeShipping row is the one that defeats a naive search. The symbol has no direct callers, but a registry holds it by name, so deleting it removes a shipping strategy that the registry still advertises. The test that covers it through the registry is the indirect evidence.

For indirect references, look for the patterns your framework uses: registries, plugin lists, dependency-injection configurations, string-based lookups, and reflection. Search configuration files and data files for the symbol’s name as a string, not just as code. The SonarSource quality framing includes reliability and clarity among the properties it cares about, and an unused-but-registered symbol is a reliability finding, not a cleanliness one.

An analyzer that reports a symbol as unused is applying its own rules about reachability. Those rules have scope limits. SonarQube Server and SonarQube Cloud document what their analyses cover, and the exact behavior differs between products and versions. Treat the analyzer’s report as a lead that focuses your investigation.

Check dynamic dispatch and configuration

Dynamic references are where deletions cause production incidents. Check them explicitly for any symbol you intend to remove.

Dynamic invocation reaches a symbol through data rather than a compiled call site. The symbol’s name appears as a string in configuration, a database row, an environment variable, a message topic, or a framework annotation processed at runtime. None of those appear in a source-level reference search.

Dynamic mechanism How to detect it Evidence that it is live If you cannot confirm
Config string naming a class Search config and env files for the name Name present in a deployed config Assume it is used
Registry populated by name Find the registry and list its entries Entry present Assume it is used
Reflection by method name Search for string forms of the name Call path exists Assume it is used
Message topic handler Check topic subscriptions Subscription active Assume it is used
Plugin discovery Check discovery conventions Convention includes the symbol Assume it is used

The default in every ambiguous row is to assume the code is used. That is the conservative choice and it is the right one. Deleting a symbol you cannot prove is unreachable is a bet against production, and the downside is much larger than the benefit of a smaller file.

Generated code is a special case. If a generator emits references to a symbol, the reference does not exist in the source tree until the generator runs. Search the generator templates as well as the generated output. Cleanup of generated output is a separate problem and outside the scope of this article.

Workflow from defining entry points through searching references, checking dynamic dispatch, classifying, and removing one unit at a time.
Editorial workflow derived from F049 through F051. The sequence is a conservative review checklist, not a guarantee that every caller is visible or that removal is safe.

Inspect public API and history

Two questions remain before a decision: is this symbol part of a published contract, and what does its history say about why it exists?

The published-contract question changes the risk. If the symbol is exported from a package that external consumers depend on, removing it is an incompatible public API change. SemVer requires a major increment for that (F049, official). Whether a symbol counts as public API depends on the project’s documented contract, so check that definition rather than assuming an internal helper is safe. An internal function with no external exposure may have no public API impact, but that has to be verified against the project’s own policy.

History adds context, not proof. Use git log to see when the symbol was introduced and how often it changed. Use git show on the introducing commit to read the intent. Use git describe to place the symbol relative to releases, which helps you tell whether it shipped in a version consumers might be using.

F050 is explicit that history alone does not establish current usage (official). A symbol that has been quiet for two years may be dead, or it may be a stable dependency nobody has needed to touch. History tells you how long the question has been open, which is useful for prioritizing, not for concluding.

History signal What it suggests Confidence Use
Added for a feature that was reverted Likely obsolete Medium Strong removal candidate
Shipped in a released version Consumers may depend on it High Compatibility review required
Never changed since introduction Stable or forgotten Low Needs usage evidence, not history
Recently modified Probably in use Medium Not a candidate

The last row is the one people get wrong. A recently modified symbol is clearly alive. A symbol untouched for years is not proven dead; it is proven quiet. Treat those differently.

Classify unused, obsolete, or external

Once the evidence is in, classify the symbol. The class determines the action, and different classes have very different responses.

Unused means no direct references, no indirect references, no entry-point status, and no public API exposure. That is the clean case and the only one where removal is straightforward.

Obsolete means the symbol supported a behavior that no longer exists, which history can help confirm. Obsolete code is a strong removal candidate, but confirm the behavior is really gone rather than relocated.

External means the symbol is reachable from outside your control: a published API, a plugin contract, a framework hook. External code is not dead just because your repository does not call it. Removing it is a compatibility event.

Classification Evidence required Action Risk
Unused No direct, indirect, or entry-point references Remove in a small diff Low, if evidence is complete
Obsolete Behavior confirmed gone, not relocated Remove, note the behavior in the message Medium
External or public API Exported or documented contract Compatibility review, then decide High
Uncertain Dynamic references unresolved Keep, or gate behind a flag Deletion risk is high

The uncertain row is the honest one. When you cannot resolve a dynamic reference, keeping the code is a legitimate outcome. Record why you kept it so the next investigation starts from your evidence rather than from scratch.

Remove one unit at a time

Removal should be a sequence of small, independent, verifiable steps. One unit per change. A unit is a function, a class, or a tightly coupled group that would be meaningless without each other.

Small steps give you three things. A failure points at one removal instead of twenty. A review can actually evaluate the evidence for one symbol. And a rollback restores one unit rather than a batch.

Removal unit Caller checks Compatibility impact Rollback note
formatLegacyDate Definition only, confirmed Internal, no public exposure Restore the function; no callers to fix
Unused enum members No references in source or config Internal Restore the members
Unregistered strategy class Registry entry already removed in prior step Internal Restore class and registry entry together
Exported helper No external references found, but exported Public API, requires review Restore and defer to a major version

The third row shows why ordering matters. If the strategy class is removed before its registry entry, the registry holds a reference to a missing class and the build or runtime fails. Remove the registration and the implementation together, or in the order that keeps every intermediate state consistent.

Each removal should keep the build green and the tests passing. If a removal requires fixing a caller, that caller was a reference and the symbol was not dead. Stop and reclassify.

Verify callers and startup paths

A deletion is not done when it compiles. It is done when the callers you kept are verified and the startup paths that could reach the removed code are exercised.

Run the tests that cover the callers adjacent to the removal. Exercise the startup path of the application, because startup is where registration-driven and reflection-driven invocation tends to surface. If the application boots and the relevant features work, the removal has passed the cheapest available evidence.

Verification What it catches What it misses When it is enough
Focused tests on remaining callers Breaks in covered callers Uncovered callers Small internal removals
Application startup Registration and wiring errors Runtime-only paths Registry and DI removals
Relevant feature smoke check Feature-level breaks Edge paths User-facing behavior
Full relevant suite Wide regressions Unexercised code Larger or riskier removals

A green run is evidence about the paths you exercised, not proof that no caller exists. The passing tests are not proof discussion is the relevant caution. Keep the diff small so that if something surfaces later, the set of possible causes is short.

Tradeoff between the readability gain from removing dead code and the risk that an unproven dynamic caller breaks at runtime.
Editorial tradeoff diagram based on F049 through F051. Removal improves readability but cannot eliminate the risk that a dynamic caller was not visible to the investigation.

Record the evidence for keeping or deleting

Whatever you decide, record the evidence. A deletion with a written rationale is auditable. A deletion with no record is a mystery the next person has to re-solve.

For a removal, put the evidence in the commit message: what checks were run, what entry points were considered, and why the symbol is believed unreachable. For a decision to keep, put a short note near the symbol or in a decision log: what was checked, what could not be resolved, and what would change the decision.

Symbol Evidence source Finding Confidence Decision
formatLegacyDate Search plus config scan No references anywhere High Remove
computeShipping Registry inspection Registered by name High Keep
renderV1Report Published package check Exported, version shipped High Defer to major version
legacyAuthHook Framework convention Hook name matches convention Medium Keep, unresolved

That last row is the useful outcome people forget to record. A kept symbol with a written reason stops the same investigation from happening every quarter. It converts an open question into a settled one, with the condition that would reopen it.

Worked example: one legacy formatter

Suppose a codebase has formatLegacyDate, a function that formats timestamps in a style the product replaced two years ago. An analyzer flags it as unused. A name search in the source tree returns only the definition.

Entry-point check: the project’s entry points are exported package symbols, HTTP handlers, and scheduled jobs. The function is not exported. It is not a handler. It is not a job.

Direct and indirect check: no source references. A search of configuration files, environment templates, and message-topic definitions for the string “formatLegacyDate” returns nothing. The project uses no reflection-based container, and the framework in use dispatches handlers by explicit registration rather than convention, so there is no convention path to check.

History check: git log shows the function was added three years ago alongside a reporting feature. git show on that commit shows the feature it supported. git describe places the introducing commit before the current major version. The reporting feature was itself removed in a later commit, which is the obsolete signal.

Classification: unused and obsolete. No direct references, no indirect references, no entry-point status, not exported. The behavior it supported is confirmed gone.

Removal: delete the function in one commit. Run the test files for the module it lived in and boot the application. Build is green, tests pass, startup succeeds.

The concrete win is one less function for every future reader of that file to evaluate, and one less false lead in the next search. The concrete loss is residual risk that some path outside the investigated surface reached it; the evidence was strong but not absolute, which is why the change was small and independently revertible.

Practical checklist and runbook

  1. Write down your project’s entry points before searching, so you know what a search cannot see.
  2. Search direct references across source, tests, build scripts, and configuration.
  3. Search indirect references through registries, dependency injection, and wrapper symbols.
  4. Check dynamic dispatch by searching for the symbol’s name as a string in config and data files.
  5. Inspect the public API surface. If it is exported, this is a versioning decision.
  6. Pull history with git log, git show, and git describe for intent and release context.
  7. Classify as unused, obsolete, external, or uncertain.
  8. Remove one unit at a time, in an order that keeps every intermediate state consistent.
  9. Verify callers and startup paths. Run the adjacent tests and boot the application.
  10. Record the evidence for the decision, including why you kept anything uncertain.
Gate Pass condition Failure response
Entry points Listed for this project Write the list before searching
Direct references Whole repository searched Widen the search
Indirect references Registries and wrappers checked Trace the indirect path
Dynamic references Config and string forms searched Assume used if unresolved
Public API Export status confirmed Route through compatibility review
Removal size One unit per change Split the batch

The practical implication: a name search is the beginning of the investigation, not the end. Spend the extra checks on anything that is exported, registered, or reachable by convention, and keep each removal small enough to revert on its own.

Control checklist covering entry points, direct and indirect references, dynamic dispatch, public API, removal size, and recorded evidence.
Editorial control checklist derived from F049 through F051. Passing every gate reduces the risk of a silent caller; it does not prove that no caller exists in every runtime.

Concrete win, honest loss, and next decision

Win: With the four checks complete, a genuinely unused symbol is removed in a small, independently revertible change. The file is easier to read, search results are cleaner, and the removal is auditable from the recorded evidence.

Loss: Static analysis cannot prove non-use in every runtime. A dynamic reference, a consumer outside your repository, or a generator convention can keep a deleted symbol alive in production. The four-check standard reduces that risk; it does not eliminate it. A batch deletion multiplies the cost of being wrong.

Implication: Default to removing dead code one unit at a time, and default to keeping anything you cannot prove is unreachable. For public API, treat removal as a versioning event and route it through your compatibility policy rather than folding it into a cleanup commit.

Verdict that reference, entry-point, history, and compatibility evidence together justify removal, while a single search does not.
Editorial verdict based on F049 through F051. The benefit is a smaller, auditable surface; the limit is that no search can prove non-use in every runtime.

Where this fits in the batch

Dead code removal is one of the cheaper quality wins in this batch. Ranking complexity hotspots covers the branching side of the same cleanup pass, and choosing reuse or independence for duplicated code covers duplicate findings, including when a quiet copy is actually unused. Baselining static analysis findings covers where unused-code findings come from and how to keep them from becoming an unusable backlog.

Removal is a behavior-preserving change, so the testing half applies directly. Mapping changed code to a check set tells you which tests protect the removal, and isolating fixture state keeps the verification clean. Snapshot review discipline applies when removal changes rendered output.

For published API, SemVer compatibility decisions govern the version impact, consumer-facing changelog entries record it, and annotated release tags tie the removal to the exact candidate. History evidence from commit messages that encode intent supports the decision.

Removals travel through review like any change. Atomic, revertible commits keep each deletion independent, choosing a merge or rebase policy governs how it lands, and recovering stashed work safely applies when a removal experiment is set aside.

For the wider workflow, the cost per verified change frames why removing unreachable code is cheap relative to refactoring it, and verification and what to ask for when it says done governs how a removal claim is checked. When removal is part of a larger cleanup, rank complexity hotspots first so deletion and restructuring stay separate decisions.

Data gap and future update

SemVer’s major-version requirement for an incompatible public API change is from the specification (F049, official). The availability of git log, git show, and git describe for history and revision context is from the Git documentation (F050, official), with the explicit caveat that history alone does not establish current usage. The four-evidence removal checklist is derived from the Git documentation rather than being a built-in feature or a guarantee that every caller is visible (F051, derived).

No measured claim is made here about how much dead code a typical codebase contains, how much removal saves, or what defect rates follow from cleanup. The fact pack contains no such benchmark. Whether a symbol is public API depends on each project’s documented contract, which is not part of the source set. Generated-code cleanup is deliberately out of scope.

Analyzer reachability rules differ between SonarQube Server and SonarQube Cloud and across versions. The cited documentation was linked and returned HTTP 200 rather than receiving a full content review of every rule page. Confirm the exact behavior against the version your repository runs. Dynamic-invocation mechanisms vary by framework, so the entry-point list must be written for your project. Documentation can change after the 2026-11-28 research date.

One AI API Key option for OpenAI-format agents

Claude Code uses an Anthropic-format route, so the One AI free model IDs are not a Claude Code model source. The research packet records Claude IDs as unavailable on 2026-11-27.

For a separate OpenAI-format agent, One AI API Key provides https://api.oneaiapikey.com/v1, a single key, and 46 live free IDs. That option concerns a different client and request format, not a way to run Claude Code. Review the free model list and eligibility details or read the quickstart before choosing an agent route.

FAQ

Is a name search with no matches enough to delete code?

No. F051 requires direct-reference, indirect-reference, entry-point, and compatibility evidence. Dynamic dispatch, reflection, configuration strings, and external consumers can all reach a symbol that a source-level search misses.

Does removing an exported function require a major version?

If it is an incompatible public API change, yes. SemVer requires a major increment for that (F049). Whether a symbol is public API depends on the project’s documented contract, so confirm before treating an internal helper as safe.

Why remove one unit at a time?

So a failure points at one removal, a review can evaluate one symbol’s evidence, and a rollback restores one unit. A batch deletion makes it hard to identify which removal caused a problem.

What if I cannot resolve a dynamic reference?

Assume the code is used and keep it. Record what you checked and what could not be resolved, plus the condition that would change the decision. A kept symbol with a written reason is a settled question.

Can an analyzer prove code is unused?

No. F050 and F051 treat history and analysis as evidence, not proof. Analyzers apply reachability rules with scope limits, and static analysis cannot prove non-use in every runtime.

More Claude Code troubleshooting

Sources

  • Official: Semantic Versioning 2.0.0, supporting the major-version requirement for an incompatible public API change (F049).
  • Official: Git log, supporting history and revision context for a removal decision (F050).
  • Official: Git show, supporting inspection of the commit that introduced a symbol.
  • Official: Git describe, supporting placement of a symbol relative to releases.
  • Official: SonarSource code quality guide, supporting reliability and clarity in the quality framing.
  • Official: SonarQube Server documentation, supporting version-specific reachability analysis behavior.
More in Blog

Try it

One API key for GPT, Grok, DeepSeek, Kimi, GLM, MiniMax, Qwen, Step, Beam, Nemotron, ERNIE, Hunyuan, Gemma, Laguna, LFM, LongCat, Llama, Solar, Jais, Mistral, K2 and Roleplay.

One AI API Key speaks the OpenAI and Anthropic formats, so you change the base URL and the key, not your code. Credit packs start at $10, and every model has a published per-token rate.

New accounts$10 credit on sign-up
  • 100requests
    per day
  • 3Mtokens
    per day
  • 47free
    models
  • $0per
    token
  • No card
  • No end date
Claim $10 credit →