Skip to navigation

Claude Code Complexity: Refactor Hotspots, Not Metrics

In short: Use complexity and debt signals to locate candidates, then justify each refactor with behavior and maintenance evidence.

Published 20 min read
On this page

Direct answer

Treat a complexity score as a way to rank where to look, not as a number to minimize. SonarSource lists cyclomatic complexity, code coverage, and technical debt ratio among the metrics it uses to describe code quality (F040, official), and it describes quality gates as conditions that can fail a build when new code misses a standard (F041, official). Those signals point at candidates. They do not decide whether a refactor is worth doing.

Before touching a hotspot, require three things: a maintenance symptom you can name, a behavior-preserving scope, and a verification plan that would catch a mistake. A file can score high and still be fine, because a long conditional chain that encodes real domain rules is not the same problem as tangled duplication. The refactor queue comes from the overlap between a high score and a real maintenance cost, not from the score alone.

The metric starts the conversation. The maintenance problem justifies the change.

Evidence map linking a complexity metric, change frequency, and a named maintenance symptom to a refactor candidate.
Editorial evidence map based on F040 through F042. The metric starts the conversation; the maintenance problem justifies the change. Not a measured defect predictor.

Why a raw score sends you to the wrong file

A complexity number is cheap to compute and easy to sort. Treating the top of the list as a backlog, ordered by severity with the highest number first, is the temptation. The problem is that the sort answers a different question from the one you care about.

Cyclomatic complexity counts independent paths through code. A parser that must handle a fixed set of document types will score high no matter how cleanly it is written, because the paths reflect the domain rather than accidental tangle. Refactoring it to satisfy a threshold can scatter a coherent rule across several files, which makes the code harder to follow even though the number improved.

The cost shows up in three ways. Review effort rises when a mechanical cleanup is mixed with a behavioral change, because the reviewer cannot tell which lines are supposed to be inert. Risk rises when a large rewrite travels with a metric fix, since a regression in an unrelated path becomes indistinguishable from the refactor. Motivation drops when the team learns that lowering a score is the goal, because the number becomes a game rather than a signal.

There is no verified threshold that predicts delivery outcomes. The fact pack contains no complexity cutoff tied to defect rates, change failure rates, or review time. Any number a tool shows you is a ranking input, and the ranking needs a second signal before it becomes work.

Read the metric definition first

Every analyzer defines its terms slightly differently, and the definition changes what a high score means. Before ranking anything, confirm what the tool is actually counting.

SonarSource lists cyclomatic complexity, code coverage, and technical debt ratio among its code-quality metrics (F040, official). Each measures something distinct. Cyclomatic complexity counts decision paths. Coverage reports which lines executed during a test run. Technical debt ratio expresses estimated remediation effort against estimated development time. A file can look alarming on one and unremarkable on another.

Metric What it counts What a high value suggests What it does not tell you
Cyclomatic complexity Independent paths through a function Many branches to read and test Whether the branches encode real domain rules
Code coverage Lines executed under test Test reach Whether assertions are meaningful
Technical debt ratio Estimated remediation effort Where effort concentrates Whether the debt actually blocks delivery
Duplication Repeated blocks Copies that may drift Whether the copies should be merged

Coverage deserves its own caution. A high line-coverage number says nothing about assertion quality. The mutation testing guide covers how to investigate whether tests would actually fail when behavior breaks, which is a different question from whether they executed.

Read the analyzer’s own documentation for the version you run. SonarQube Server and SonarQube Cloud document their rule sets and how findings are computed, and the details differ between products and versions. A threshold copied from a blog post, including this one, is not a substitute for the definition your tool applies.

Locate high-change hotspots

The strongest ranking signal combines complexity with change frequency. A file that scores high and changes rarely is a curiosity. A file that scores high and changes every sprint is where maintenance cost actually accrues.

Change frequency comes from history, not from the analyzer. Use git log and git show to see which files absorb the most commits and which commits touched them. The facts-versus-hypotheses debug log habit applies here too: record what the history shows before deciding what it means.

Hotspot Metric Change frequency Maintenance symptom
OrderTotals.cs Cyclomatic complexity 34 18 commits in 90 days Every pricing change breaks a neighboring rule
renderDocument.ts Cyclomatic complexity 27 4 commits in 90 days High score, stable behavior, no recent pain
AuthMiddleware.java Technical debt ratio high 11 commits in 90 days Reviewers re-read the same logic each change
formatCurrency.ts Cyclomatic complexity 12 2 commits in 90 days Low signal despite a nonzero score

OrderTotals.cs and AuthMiddleware.java are the candidates. renderDocument.ts has a worse score than formatCurrency.ts and less reason to change. formatCurrency.ts is not on the list at all.

Ranking by score alone would have sent you to renderDocument.ts. Ranking by score plus change frequency plus a named symptom sends you where the cost is. Here is the whole difference between a metric and a queue.

Separate complexity from poor naming

Not every readability problem is a complexity problem. A function can have modest branching and still be hard to follow because names are vague, because responsibilities are mixed, or because the data it reads and writes is not obvious. Renaming and decomposition are different edits with different risks.

Before proposing a refactor, ask which problem you are actually solving. If the answer is “the names are unclear,” the fix is renaming, and it can often be done in a small, easily reviewed diff. If the answer is “these branches encode two unrelated concerns,” the fix is separation, and it needs a behavior boundary. If the answer is “I cannot tell what this does,” the first step is writing down the intended behavior, not moving code.

Symptom you observe Likely problem Right first edit Risk if misdiagnosed
Branches encode distinct concerns Accidental complexity Separate the concerns behind a boundary Scattering a coherent rule
Names hide intent Naming Rename within the same structure Churning a large diff for little gain
One function does setup, logic, and IO Mixed responsibility Extract cohesive pieces Breaking ordering or side effects
Deep nesting from repeated guards Control flow shape Invert guards or combine conditions Changing which branch executes first
Long conditional chain over a fixed set Domain enumeration Leave it; document the set Turning a clear rule into indirection

The last row matters. A long chain over a fixed, documented set of cases is often the clearest representation of the domain available. Replacing it with a lookup table or a strategy registry can hide the set and make it harder to audit. Refactor that only when the set changes often enough that the structure pays for itself.

Choose one behavior-preserving refactor

Pick a single, bounded refactor unit. One function, one class, one module. The unit should be small enough that a reviewer can hold the before and after in mind at the same time.

Behavior-preserving means the observable contract does not change. Inputs produce the same outputs, errors surface in the same way, ordering guarantees hold, and side effects occur in the same sequence. If a change alters any of those, it is a behavior change and belongs in its own review, not inside a complexity cleanup.

Refactor unit Behavior protected Test scope Reviewer focus
Extract a pricing rule into its own function Same totals for the same inputs Existing pricing tests, plus boundary cases No change to rounding or ordering
Split setup from computation Same side effects in same order Integration tests touching the setup Effects still fire before consumers read
Replace nested guards with early returns Same rejection conditions Tests covering each guard No guard becomes unreachable or reordered
Introduce a named type for a flag Same accepted values Type-level checks plus call sites No accepted value silently drops

Keep the diff bounded. A bounded diff is one where the reviewer can enumerate what changed and why without reading the whole file. If a refactor proposal grows past that, split it. Mixing a large rewrite with a metric cleanup makes both harder to review and neither safer to ship.

Protect the existing test boundary

A refactor without a test boundary is a rewrite with extra steps. Before editing, establish what would catch a mistake.

The cheapest protection is a characterization net: tests that record current behavior for representative inputs, including the awkward boundaries. If the hotspot has no tests, write a few that assert observable behavior before changing structure. These tests are not a claim that the code is correct; they are a claim about what it currently does, which is exactly what a behavior-preserving refactor must preserve.

SonarSource includes code coverage among its quality metrics (F040, official), and coverage tells you which lines a test run reached. Coverage does not tell you whether the assertions would fail if behavior changed. Pair coverage with tests you have actually read, and use the mutation testing approach when you suspect the assertions are weak.

Protection level What it catches What it misses When it is enough
Existing focused tests Regressions in covered paths Untested boundaries Hotspot already has meaningful tests
Added characterization tests Current behavior drift Cases nobody wrote down Hotspot has thin or no tests
Type and contract checks Signature and shape breaks Behavioral changes within a type Refactor moves code between modules
Full relevant suite Wide regressions Behaviors no test exercises Refactor touches shared infrastructure

Jest configuration documents how test projects and file matching are set up, which matters when a refactor spans directories and you need the right tests to run. Configure test selection deliberately rather than assuming a broad run will cover the refactor.

Workflow from reading the metric definition through ranking hotspots, choosing a bounded unit, protecting tests, and verifying the diff.
Editorial workflow derived from F040 through F042 and the cited documentation. The sequence is a recommended review method, not an official Claude Code procedure.

Review the diff for accidental scope growth

The most common failure in a complexity refactor is scope growth. A cleanup starts as extracting one function and ends touching twelve files because a name improved, a dependency moved, or an unrelated bug got fixed along the way.

Review the diff specifically for scope. Ask three questions of every changed file. Does this change belong to the stated refactor unit? Would reverting this file alone break the refactor’s intent? Does this change alter observable behavior, even slightly?

Review question Passes when Fails when Action
Does each file belong to the unit? Changes trace to the stated goal Unrelated cleanup rides along Split the diff
Is behavior identical? Observations match before and after Any output, error, or ordering differs Reclassify as a behavior change
Is the diff bounded? Reviewer can enumerate the change Review spans many files Split further
Are tests behavior-preserving? Assertions describe current behavior Tests were weakened to fit Restore the assertions
Did the metric improve for the right reason? Structure genuinely simplified Number dropped via indirection Reconsider the approach

That last row is the subtle one. A score can drop because the code got simpler, or because complexity was pushed into a callback, a configuration object, or a generated lookup. The number improves and the reading experience does not. Look at the code, not only the dashboard.

Ask Claude Code for the maintenance evidence

Use the agent to gather the evidence that justifies the refactor, rather than to generate the largest possible diff. Ask for the change history of the hotspot, the tests that currently exercise it, and a written restatement of the behavior the refactor must preserve.

Official best practices recommend precise prompts with file names and symptoms, and a pass-or-fail check so the agent can close a work loop. Applied here: name the file, name the symptom, and give the agent the test command that should still pass after the change. The agent can then produce a bounded proposal and verify it against that check.

A useful prompt shape:

This file changes every sprint and reviewers re-read the same branching each time. Restate the current observable behavior for these inputs, list the tests that cover it, and propose one behavior-preserving refactor that reduces the branching without changing any output, error, or ordering. Do not change public signatures.

Ask for the maintenance evidence explicitly. The legacy code and tribal knowledge guide covers the related problem of behavior that exists only in people’s heads. Characterization tests turn that tribal knowledge into something the refactor can be checked against.

Track outcome without a universal target

Decide in advance how you will know the refactor helped, using evidence you can actually collect. The honest options are maintenance-shaped, not score-shaped.

Useful outcome signals include: fewer review comments about the same logic on the next change, a smaller diff for the next feature in that area, fewer regressions traced to that file in the next few sprints, and faster onboarding when a new engineer reads it. These are observations a team can record without inventing numbers.

What you cannot honestly claim is a universal threshold. There is no verified complexity cutoff that predicts delivery outcomes, no verified defect rate tied to a score, and no verified review-time saving from a cleanup. The ranking workflow itself, using metrics to rank candidates and requiring a maintenance symptom plus a verification plan before refactoring, is a recommendation derived from the vendor guidance rather than a SonarSource or Claude Code mandate (F042, derived).

Outcome signal How to observe it Honest caveat Review date
Review comments on the logic drop Compare review threads before and after Depends on reviewer and change type Next quarter
Next diff in the area is smaller Compare line counts for similar features Features differ in scope Next feature
No new regressions traced here Track incident and bug links Absence of evidence is weak Next quarter
Onboarding reads faster Ask the next engineer directly Subjective, small sample Next hire

The practical implication: pick a small number of signals you will actually check, write down the date you will check them, and accept that some refactors will show no measurable benefit. That is a real result, not a failed one.

Tradeoff between a lower complexity score and the risk of scattering a coherent domain rule across files.
Editorial tradeoff diagram based on F040 through F042. A lower metric is not proof of better code; indirection can improve the number while harming readability.

Quality gates as a regression block

Quality gates are worth separating from refactoring. SonarSource describes a quality gate as a set of conditions applied after analysis that can fail a build when new code misses the standard (F041, official). The useful framing is directional: a gate on new code can stop the situation from getting worse without requiring you to fix the existing codebase first.

The distinction that matters is between new code and inherited code. A gate that fails the build because an old file crosses a threshold forces either a mass cleanup or a suppressed rule, and both are worse than the problem. A gate scoped to new or changed code lets the team raise the floor gradually.

Gate scope Effect Risk When it fits
New code only Stops the floor from dropping Reviewers may game the boundary Large existing codebase
New and changed code Improves touched areas over time Slower changes in hotspots Active development area
Whole repository Forces immediate compliance Mass suppression or cleanup Greenfield or mandated reset

Enforcement depends on the repository’s integration and policy, not on the metric definition. Whether a gate actually blocks a merge is a property of your branch protection and CI wiring. The branch protection and merge checks guide covers how to prove a required check really blocks an incomplete pull request, and the merge queue guide covers grouped validation. Do not assume a rule exists just because the dashboard shows a number.

Static analysis findings need their own baseline strategy, covered separately in baselining static analysis noise. That post handles inherited findings and suppressions; this one is about turning a complexity signal into a bounded refactor.

Worked example: one pricing function

Suppose OrderTotals.cs computes a total across a discount, a tax rule, and a rounding policy, with a cyclomatic complexity of 34 and eighteen commits in ninety days. The symptom is concrete: every pricing change breaks a neighboring rule, and reviewers re-read the same block each time.

Step one is reading the metric definition for the installed analyzer version, so the number is understood rather than feared. Step two is history: the eighteen commits are the reason this file outranks a higher-scoring file that rarely changes.

Step three is the test boundary. Before moving anything, write characterization tests for the awkward boundaries: an empty order, a discount larger than the subtotal, a tax rule that changes mid-calculation, and the rounding boundary. Each test asserts the current observable total.

Step four is a single bounded refactor. Extract the discount rule into a function that takes the subtotal and returns the discounted amount, keeping rounding and ordering identical.

Derived arithmetic for a review fixture, using stated inputs only: subtotal 100, discount rate 0.10, tax rate 0.08. Discounted subtotal = 100 - (100 x 0.10) = 90. Tax = 90 x 0.08 = 7.2. Total before rounding = 90 + 7.2 = 97.2. These inputs and the formula come from the fixture, not from any benchmark, and they exist so the after-state can be compared line by line with the before-state.

The concrete win is a smaller review surface: the next pricing change touches one extracted function and the reviewer reads one rule instead of a 34-branch block. The concrete loss is that the extraction is only justified if pricing keeps changing; if the file goes quiet, the refactor bought structure that nobody needed. Change frequency belongs in the ranking for this reason.

Control checklist covering metric definition, hotspot ranking, bounded unit, test protection, diff scope, and outcome signals.
Editorial control checklist derived from F040 through F042. Passing the checklist improves reviewability; it does not prove the refactor was necessary or that the metric now predicts anything.

Practical checklist and runbook

  1. Read the metric definition for the installed analyzer and version. Confirm what the number counts.
  2. Pull change frequency with git log. Rank by score plus frequency plus a named symptom.
  3. Name the maintenance symptom. If you cannot name one, the file is not a hotspot yet.
  4. Classify the problem. Accidental complexity, naming, mixed responsibility, or domain enumeration.
  5. Choose one bounded unit. One function, class, or module. Write down what is in and out of scope.
  6. State the protected behavior. Outputs, errors, ordering, side effects that must not change.
  7. Build the test boundary. Add characterization tests for boundaries before changing structure.
  8. Make the edit. One refactor, one diff. No unrelated cleanup.
  9. Review the diff for scope growth. Split anything that stops being enumerable.
  10. Record an outcome signal and a review date. Check it later and accept a null result honestly.
Gate Pass condition Failure response
Metric definition You can state what is counted Read the analyzer docs first
Hotspot Score plus frequency plus symptom Remove files with no symptom
Problem class Named and matched to the right edit Do not rename your way past tangle
Unit boundary Reviewer can enumerate the change Split the diff
Test protection Behavior-preserving assertions exist Add characterization tests
Behavior Identical before and after Reclassify as a behavior change
Verdict that metrics rank attention usefully but cannot substitute for a maintenance symptom and a verification plan.
Editorial verdict based on F040 through F042. The benefit is a defensible refactor queue; the limit is that no verified threshold predicts delivery outcomes.

Where this fits in the batch

Complexity ranking is one input among several quality signals. Deciding whether to reuse or keep code independent handles the duplication half of the same ranking problem, including when copies should stay separate. Baselining static analysis findings covers inherited debt so a new gate does not become an unusable backlog.

Removing dead code with usage evidence is often a better first move than refactoring a hotspot, because deletion shrinks the surface without changing behavior. Recovering stashed work safely applies when a refactor experiment needs to be set aside without losing it.

On the testing side, mapping changed code to a check set tells you which tests protect a refactor, and isolating fixture state keeps the characterization net from leaking between cases. Snapshot review discipline applies when a refactor changes rendered output that should not have changed.

Refactors travel through review. Splitting work into revertible commits keeps a cleanup reviewable, and resolving merge conflicts by behavior applies when two refactors touch the same block. Choosing a merge or rebase policy governs how the cleanup lands.

Version impact belongs to its own decision. SemVer compatibility choices govern public API changes, and a refactor that alters a published signature is a versioning question, not a cleanup. Writing consumer-facing changelog entries records the impact when behavior does change.

For the wider workflow, verification and what to ask for when it says done governs how a refactor claim is checked, and the cost per verified change frames why a bounded diff is worth protecting.

Data gap and future update

The metric list and the quality-gate description come from the SonarSource vendor guide (F040 and F041, official). This is vendor framing, not independent proof that any threshold predicts delivery outcomes. No complexity cutoff, defect rate, review-time saving, or coverage target is claimed here, because the fact pack contains none.

The ranking workflow, requiring a maintenance symptom and a verification plan before refactoring, is derived from the vendor guidance rather than mandated by SonarSource or Claude Code (F042, derived). Treat it as an adaptable review method.

Version-specific rule behavior for SonarQube Server and SonarQube Cloud was drawn from linked documentation that returned HTTP 200 rather than a full content review of every rule page. Confirm the exact metrics and gate conditions against the version your repository runs. Documentation and thresholds 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 use the cost calculator before choosing an agent route.

FAQ

Is there a complexity threshold a team should enforce?

No verified one. F040 lists cyclomatic complexity among quality metrics but establishes no cutoff tied to delivery outcomes. Pick a ranking input, not a rule, and justify each refactor with a named maintenance symptom.

Does a lower complexity score mean better code?

Not necessarily. A score can drop because complexity moved into a callback or a lookup rather than disappearing. Read the code after the change. F042 labels the ranking workflow as a recommendation, not a quality guarantee.

Should a complexity refactor change public signatures?

Treat that as a separate decision. Changing a published signature is a compatibility question governed by your versioning policy. The SemVer compatibility guide covers how to classify it.

How do I protect a refactor in a file with no tests?

Write characterization tests that record current observable behavior for representative and boundary inputs before changing structure. That is a claim about what the code does now, which is exactly what a behavior-preserving change must preserve.

Can a quality gate replace the need for review?

No. F041 describes gates as conditions that can fail a build. Whether a gate blocks a merge depends on your branch protection and CI wiring, and it does not judge whether a refactor was necessary.

More Claude Code troubleshooting

Sources

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 →