Code Quality Metrics: Which Ones to Track and How to Read Them
Code quality metrics explained: complexity, duplication, coverage, churn, defect density and DORA. What each shows, how it misleads and how to combine them.
In this article:
- Start with the question, not the dashboard
- Structural metrics: complexity and duplication
- Test coverage: a floor, not a goal
- Code churn and hotspots: where change hurts
- Outcome metrics: defect density and DORA
- Code quality metrics at a glance
- How to roll out code quality metrics in six steps
- Conclusion
Start with the question, not the dashboard
Code quality metrics are only useful when they answer a decision someone actually has to make. “Is our code good?” is not such a question. “Can we change the billing module safely next quarter?”, “Where are our incidents coming from?” and “Is the new team making the codebase better or worse?” are.
Most teams invert this. They install a static analysis tool, receive a few thousand findings and a letter grade, and then try to work out what the numbers mean. A few months later the dashboard is open in nobody’s browser.
A more reliable approach is to group metrics by the question they answer. Four families cover almost every situation:
- Structural metrics (complexity, duplication): how hard is the code to understand and change?
- Safety-net metrics (test coverage): how likely is a change to break something unnoticed?
- Change metrics (churn, hotspots): where is the team actually spending its effort?
- Outcome metrics (defect density, DORA): what is code quality costing in production and in delivery speed?
The first three are leading indicators: they move before problems show up. The fourth family is lagging: it tells you what has already happened. You need both. Leading indicators without outcomes turn into an aesthetic debate, and outcomes without leading indicators arrive too late to act on.
Structural metrics: complexity and duplication
Cyclomatic and cognitive complexity
Cyclomatic complexity counts the independent paths through a function: every if, loop, case and boolean operator adds one. It is a good proxy for how many tests a function needs to be fully exercised and how much a reader must hold in their head. Thomas McCabe, who defined it in 1976, proposed 10 as a reasonable upper limit per function, and many teams still use that as a starting point. We cover thresholds and refactoring patterns in cyclomatic complexity explained.
Cognitive complexity, introduced by SonarSource, fixes a known weakness of the cyclomatic count. A flat switch with twenty cases scores high but is easy to read, while three nested loops with early exits score lower and are much harder to follow. Cognitive complexity penalises nesting and breaks in linear flow, so it tracks human effort more closely.
Two reading rules matter more than the exact threshold. Look at the distribution, not the average: a codebase with a low mean can still hide a handful of functions nobody dares to touch. And read complexity together with change frequency, which we return to below.
Duplication
Code duplication measures blocks of code repeated across the codebase, usually as a percentage of lines. Its real cost is not size but divergence: a bug fixed in one copy survives in the others, and the copies drift apart until nobody knows which one is correct.
Duplication tools detect copy-paste clones well and semantic duplication poorly, meaning the same business rule written twice in different ways. Treat the number as a lower bound. Also accept that some duplication is the right call: two services carrying a near-identical DTO is often cheaper than a shared library that couples their release cycles.
Test coverage: a floor, not a goal
Test coverage reports the share of lines or branches executed by the automated test suite. Branch coverage is more informative than line coverage, because it shows whether both sides of each condition were exercised.
Coverage answers one question well: which code is definitely not tested? It answers a second question badly: is the tested code tested well? A test that calls a function and asserts nothing still produces coverage. Once coverage becomes a target, teams learn to write exactly that kind of test.
Three practices keep coverage honest:
- Measure coverage on new and changed code, not only the global figure. A legacy system cannot jump from low to high coverage in a quarter, but every pull request can meet a bar. In our fintech engagement, the 85% coverage we report applies to the newly extracted modules, not to the eight-year-old PHP monolith they were carved out of.
- Weight by criticality. Coverage on payments, authentication and data ingestion matters far more than coverage on an internal admin screen.
- Spot-check with mutation testing. Tools such as PIT for Java or Stryker for JavaScript and .NET inject small faults and check whether the tests notice. Mutation testing is slow, so run it periodically on critical modules rather than on every build.
Code churn and hotspots: where change hurts
Code churn is how often a file or module changes, typically measured from version control as commits or modified lines over a period. Churn alone is neutral: a feature under active development should churn. What matters is where churn meets complexity.
A hotspot is a file that is both complex and frequently changed. This combination, popularised by Adam Tornhill’s work on behavioural code analysis, is usually the most actionable view a team can get. A complex module that nobody touches is a sleeping risk. A complex module that half the team edits every sprint is where your bugs, merge conflicts and slow reviews come from.
You do not need special tooling to start. A short script over git log that counts commits per file over the last six months, joined with per-file complexity from your static analysis tool, produces a ranked list in an afternoon. The top of that list is almost always where refactoring pays back fastest.
Also watch for files in different modules that always change together. This change coupling reveals dependencies the architecture diagram does not show.
Outcome metrics: defect density and DORA
Defect density
Defect density is the number of confirmed defects per unit of size, usually per thousand lines of code (KLOC), for a given module and period. Its value is comparative: it shows which parts of the system generate a disproportionate share of bugs relative to their size.
To make it useful, define what counts as a defect (production incidents only, or bugs caught in QA as well), attribute each one to the module where the fix landed, and compare modules within the same codebase. Defect density across different languages, teams and counting rules is not comparable, so resist the urge to benchmark it against external figures.
The four DORA metrics
The DORA metrics measure delivery performance: deployment frequency, lead time for changes, change failure rate and time to restore service. They are not code metrics, but poor code quality shows up in them quickly. Fragile modules raise the change failure rate, and tangled dependencies stretch lead time because every change needs more coordination and more testing.
The 2023 DORA report infographic describes elite performers as deploying on demand, with lead time under one day, a change failure rate of 5% and recovery in under an hour. Use these as a direction of travel, not a pass/fail line. Our DORA metrics guide explains how to collect each one from your pipeline.
Outcome metrics matter even more as AI-assisted coding spreads. The DORA 2024 report estimated that increased AI adoption went with a 7.2% reduction in delivery stability. More code produced faster is only good news if change failure rate and defect density hold steady.
Code quality metrics at a glance
| Metric | Question it answers | How to measure | How it misleads |
|---|---|---|---|
| Cyclomatic complexity | How many paths must be tested? | Static analysis, per function | Averages hide outliers; flat switches score high |
| Cognitive complexity | How hard is this to read? | Static analysis, per function | Says nothing about correctness |
| Duplication | Where will fixes diverge? | Clone detection, % of lines | Misses semantic duplication |
| Test coverage | What is definitely untested? | Coverage tool in CI, branch level | Assertion-free tests inflate it |
| Code churn | Where is effort going? | Version control history | High churn can be perfectly healthy |
| Hotspots | Where does change hurt most? | Churn joined with complexity | Needs months of history to be reliable |
| Defect density | Which modules generate bugs? | Defects per KLOC per module | Depends entirely on counting rules |
| DORA metrics | How fast and safely do we deliver? | CI/CD and incident data | Can be gamed with trivial deployments |
If you need to condense these into a single view for leadership, our article on the technical debt dashboard covers which aggregates hold up in a board meeting and which ones mislead.
How to roll out code quality metrics in six steps
- Write down the decisions. List the two or three questions the metrics must answer this year: where to refactor first, whether a migration is safe to start, whether quality is improving or eroding.
- Pick one metric per family. For example cognitive complexity, branch coverage on changed code, a hotspot ranking and change failure rate. A few metrics reviewed consistently beat a wall of charts.
- Take a baseline before changing anything. Record current values per module, not only global numbers, so later improvements can be shown and attributed to specific work.
- Gate new code, not old code. Configure a quality gate in CI that applies to the diff: no new function above your complexity limit, a minimum coverage on changed lines, no new duplicated blocks. This stops the problem growing without blocking the team on years of legacy findings.
- Review trends on a fixed cadence. A short monthly review of the hotspot list and the outcome metrics, with one concrete refactoring decision as its output, keeps the numbers connected to real work.
- Never use them to rate individuals. The moment complexity or coverage appears in performance reviews, people optimise the number instead of the code, and the metrics stop telling you the truth.
Conclusion
Code quality metrics work when each one is tied to a question and read alongside the others. Complexity and duplication tell you how hard the code is to change, coverage tells you how safely, churn and hotspots tell you where it matters, and defect density and DORA tell you what it is costing. No single number does all of that, and no tool can decide on its own which module is business-critical.
If you want an independent reading of your codebase, with these metrics measured per module and turned into a prioritised, incremental plan, our code audit is where we start. The first 30-minute call is free.