Code Quality Metrics: 23 Defect Markers That Predict Bugs

Raghav ChamadiyaUpdated 12 min read
Compared in this post: repowise and
  • CodeScene
  • SonarQube Server
On this page

Code quality metrics are numbers computed from source code and its change history that estimate how hard code is to change safely and how likely it is to contain bugs. The classic ones are cyclomatic complexity, duplication, coupling, coverage and churn. This post lists each with a threshold, shows which ones point at defects in our data from 160 public repos, and covers the 23 markers repowise scores per file.

Part of the code quality guide. This post covers code-level metrics, the ones you can compute from a repository. Wider software quality metrics such as defect density in production are out of scope.

Code quality metrics at a glance

Most code metrics fall into four groups: size, complexity, structure and process. The table gives the usual way to compute each, a threshold people commonly use, and whether it earns its place as a bug predictor. Thresholds are conventions, not laws. Treat them as a flag to look, not a verdict.

MetricWhat it measuresHow to computeCommon thresholdPredicts defects?
Cyclomatic complexityIndependent paths through a functionDecision points plus one10 per function (McCabe)Weakly alone; stronger with churn
Cognitive complexityHow hard a function is to readBranches, weighted up by nesting15 per function (SonarQube default)Weakly; better for review than prediction
LOC and NLOCSize, with and without comments and blanksCount linesNo standard; 50 lines is a common rule of thumbSize is the confounder behind most other metrics
Nesting depthLevels of indentation in a functionDeepest block level4Moderately, through complexity
DuplicationCopy-pasted codeShare of lines in duplicate blocks3% or less on new code (SonarQube default gate)Weak alone; stronger when copies change together
Coupling and fan-inHow many files depend on this oneCount importers and importsNo standard; read it per repoModerate, as blast radius
Cohesion (LCOM)Whether a class's methods share fieldsLCOM4 connected groups1 groupWeak
Test coverageCode exercised by testsCovered lines over executable lines80% on new code (SonarQube default gate)Weak alone; useful on busy files
Code churnHow much a file changesLines added plus deleted in a windowNone; rank within the repoStrong
Halstead metricsVolume and effort from operators and operandsCounts of distinct and total operatorsNone in practiceWeak, and tracks size
Maintainability indexOne composite of Halstead, complexity and LOCThe 1991 formula, scaled 0 to 100Microsoft's Visual Studio flags 0 to 9 as red and 10 to 19 as yellowWeak
Defect densityBugs per thousand linesConfirmed defects over KLOCNone; compare to your own pastIt is the outcome, not a predictor
Technical debt ratioRemediation cost against build costFix time over rewrite time5% or less for an A (SonarQube rating)Indirect

Scroll the table sideways to see every column.

For formulas and worked examples of the complexity rows, code complexity metrics goes through them one by one. For the coverage row, see test coverage. The standard behind most of these categories is ISO 25010, which names maintainability, reliability and the rest as quality characteristics and leaves the numbers to you.

What the data says about code quality metrics

Metrics earn trust when you can see how they behave on real code. We measured two cohorts of public repositories indexed on repowise.dev (1,000+ GitHub stars each, production files only, tests and generated code excluded).

Complexity is common and concentrated

In our 24 November 2026 pull of 160 repos and 200,744 production files, 23.3% of files contain a function above McCabe's limit of 10, 9.9% contain one above 20, and 2.1% (4,178 files, in 133 repos) contain one above 50. The median file is calm: half of all files have a worst function of 4 or less. The tail is long, with a 99th percentile of 73. These are per-file maxima, since the data gives each file's worst function and not every function.

Complexity piles up in a few places. In the median repo, the top 10% of files hold 86.9% of all complexity above the limit of 10. Language matters too. JavaScript repos run hottest at 44.0% of files with a function above 10, against 28.6% in TypeScript, 22.2% in Python, 20.5% in Rust and 17.4% in Go.

How file health tracks complexity

Worst function in fileFilesMedian file health (0 to 10)Files scoring below 4Median NLOC
1 to 10154,01510.00.4%42
11 to 2026,9068.047.9%170
21 to 5015,6456.2122.4%274
51 and above4,1783.0959.5%595

Scroll the table sideways to see every column.

Complexity is one input to the health score, so this table shows how the score treats complexity, not independent proof of bugs. It does show how size and complexity travel together: 61.4% of files over 1,000 NLOC contain a function above 20, against 3.6% of files of 200 NLOC or fewer.

Low scores do point at bugs

The independent check is bug history. Across 173 repos with enough fix history (from a cohort of 195 repos, data pulled 10 November 2026), the least-healthy 20% of files hold a median 60% of the files that needed a bug fix in the last 180 days. The 20 lowest-scoring files in a repo were bug-fixed 5.4x as often as the average file. A file counts as bug-fixed when a fix: commit touched it, so this is an association on history, not a forecast.

Change is just as lopsided. In the median repo, 10% of production files take 68% of 90-day line churn. That is why a per-file view beats a repo average: the quality problem lives in a small set of files, and a mean smooths it away.

Process metrics vs structural metrics

Structural metrics read a snapshot of the code. Process metrics read how the code changed. Cyclomatic complexity, nesting and duplication are structural. Churn, co-change, change entropy and ownership are process metrics.

When we compared them across 21 repositories with file size controlled, the process side won. Co-change scatter was the strongest single signal, ahead of file size, with change entropy and ownership risk next and complexity after that. The method is in process metrics beat structural metrics.

Use structural metrics where history does not exist: a fresh clone, a new file, a pull request diff. Use process metrics to decide which of the complex files to fix first. A complex file nobody touches is cheap. A complex file that changes every week is where defects come from.

The 23 markers repowise scores

repowise turns these metrics into 23 markers that feed one per-file score from 1 to 10. It registers 59 detectors in all; the rest feed the separate maintainability and performance signals. How the score is computed deduction by deduction is in the scorer internals post, and the wider idea of code health is in the code health guide.

Each file starts at 10. Every finding deducts its severity times its marker weight, deductions are capped per family so no single family dominates, and the result is clamped to 1 to 10. Bands are absolute, so a 6.2 means the same in every repository.

BandScoreMeaning
Excellent8.5 and aboveLow risk, easy to change
Good7.0 to 8.5Sound; nothing demands attention
Fair5.5 to 7.0Rising complexity or process risk
Needs work4.0 to 5.5Worth scheduling
At riskunder 4.0Where defects concentrate

Scroll the table sideways to see every column.

A repowise file page showing a code health score of 8.3 out of 10 in the Good band, with lines, symbols, dependents and test coverage beside it
A repowise file page showing a code health score of 8.3 out of 10 in the Good band, with lines, symbols, dependents and test coverage beside it

A file page in repowise's own repository: the score, its band, and the dependency and test context beside it.

The scored markers fall into families: structural complexity, size, duplication, error handling, change history, and test coverage and quality. The grouping matters more than the exact thresholds. Full detector roster: code health architecture docs.

Complexity

MarkerFlags
Complex methodFunctions with cyclomatic complexity (CCN) of 9 or more
Nested complexityFunctions nested 4 or more levels deep
Bumpy roadSeveral medium-depth nesting humps side by side
Large methodBodies of 60+ lines that also carry branching
God classA class of 200+ NLOC with 15+ methods and a brain method
Complex conditionalConditions glued from three or more boolean operators
Function hotspotFunctions that are both complex and frequently modified

Scroll the table sideways to see every column.

Design and duplication

These deduct at half weight in the defect score, because on their own they proved weak bug predictors. The maintainability signal counts them in full.

MarkerFlags
Brain method70+ lines, CCN 9+, in a file many others import
Low cohesionA class whose methods split into groups sharing no fields (LCOM4 of 2 or more)
Long parameter listFive or more raw parameters that want to be one object
DRY violationDuplicated code, weighted up when copies change together
Error handlingSwallowed or catch-all handlers, Rust unwrap and panic!, ignored Go errors

Scroll the table sideways to see every column.

Coupling

MarkerFlags
Co-change scatterA file coupled to many distinct co-change partners (shotgun surgery)
Knowledge lossA bus factor of 1 where that author has left or makes under 20% of recent commits

Scroll the table sideways to see every column.

Test signal

MarkerFlags
Untested hotspotA churning, widely imported file with no meaningful coverage
Coverage gapSignificant uncovered surface in a non-trivial file (needs a coverage report)
Coverage gradientA continuous deduction proportional to the uncovered fraction
Large assertion blockOne test with 15+ consecutive assertions
Duplicated assertion blockCopy-pasted assertion sequences across tests

Scroll the table sideways to see every column.

Churn signal

MarkerFlags
Churn riskChurn normalised by file size, a stronger predictor than raw churn
Change entropyChanges scattered across wide, noisy commits
Code age volatilityDormant code that is suddenly modified again
Developer congestion5+ contributors, top-quarter churn, nobody owning half
Ownership riskMany drive-by authors, none above 40%
Prior defectRecent bug-fix history, the cheapest predictor of the next fix

Scroll the table sideways to see every column.

History amplifies code risk; it does not stand alone. Git history costs a file at most 1.0 point, plus one point for each point its code-shape findings deduct, up to 3.5. A simple file that changes often reads as busy, not broken, and never drops below 9.0 from history alone.

Does the score predict bugs?

Yes, measurably. repowise scored files at a historical commit and checked them against the next six months of bug fixes, with nothing after that commit feeding the score. ROC AUC was 0.74 across 21 repositories and 9 languages, +0.10 AUC over ranking by recent churn, and 0.76 to 0.78 on the external PROMISE/jEdit corpus. Against CodeScene on the same files, repowise surfaced 2.3x the defects under a 20%-of-lines review budget. Method and reports: benchmarks.

From score to decision

A per-file score is useful when it says what would make the file safer to touch. In repowise:

bash
repowise init             # full index; scores every file, no LLM key
repowise health           # fix first, KPIs, lowest-scoring files
repowise health --trend   # the last 10 snapshots
repowise next             # the short cross-layer to-do list

Agents get the same data through the get_health MCP tool, per repo or per file. Then triage the lowest files:

PatternLikely fix
High complexity, low churnRefactor only when you next touch it
High complexity, high churnSchedule a dedicated cleanup
Widely imported, low coverageAdd characterization tests first, then split
Many co-change partnersRevisit module boundaries
Knowledge loss on an active filePair on it and write down the decisions

Scroll the table sideways to see every column.

The fix-first list ranks one unit of work per item with the first edit, expected gain, effort and the tests to run. For a larger refactor, see refactoring priorities by impact per effort. A falling score says more than a low one, which is the subject of declining code health trends.

FAQ

What are code quality metrics?
Code quality metrics are measurements taken from source code and its version history that estimate how easy the code is to change and how likely it is to hold defects. Common examples are cyclomatic complexity, duplication, coupling, test coverage and code churn.
What are the most important code quality metrics?
Start with cyclomatic complexity per function, code churn per file and test coverage on the files that change most. In our data the least-healthy 20% of files hold a median 60% of bug-fixed files, so complexity and churn together tell you more than any single number.
How do you measure code quality?
Pick a few metrics, compute them per file or per function instead of per repository, and track the trend. A workable starter set is cyclomatic complexity per function, churn per file, duplication and coverage on changed code. A static analyzer gives complexity, duplication and coupling. Your git history gives churn and bug-fix counts. repowise combines both into one score per file.
What is a good code quality metric?
A good metric is cheap to compute, hard to game and tied to an outcome you care about, such as bug fixes or review time. Churn and co-change meet that bar in our 21-repo study. Lines of code and the maintainability index mostly track file size.
What is a good cyclomatic complexity?
McCabe's original limit is 10 per function, and most tools flag above that. In our data from 160 public repos, 23.3% of files have at least one function above 10, so a hard rule flags a lot. Fix the functions that are also changing often.
Does repowise need an LLM key to score code quality?
No. Scoring reads the parse tree, the dependency graph and git history, and runs inside repowise init and repowise update.