Zest
code quality

How to Measure Code Quality: 12 Metrics, Tools and AI Code

By Zest | Updated | 12 min read

Related guide: Developer productivity metrics for AI-assisted teams

A laptop on a desk showing a code editor with a check mark and the words Quality That Matters, in front of two monitors

To measure code quality, combine three kinds of signal, because no single number captures it: code metrics from a static analyzer, test metrics, and outcome metrics from delivery such as change fail rate. Pick three to five, check the code metrics on new code in CI, and read the trend over months.

Zest links each engineer's coding-agent sessions to the pull requests they led to, so you can see which agents and models wrote the pull requests your quality checks flag. Start free

Google learned the same lesson about technical debt: it explored 117 metrics proposed as indicators of three kinds of debt, and “no single metric predicted reports of technical debt from engineers” (Ciera Jaspan and Collin Green, “Defining, Measuring, and Managing Technical Debt”, IEEE Software, 2023). Outside claims below link their source; our own numbers come from one small team’s repositories.

What is code quality?

Code quality is how well code does its job and how cheaply it can be changed without breaking. The ISO/IEC 25010 product quality model names nine quality characteristics, and the one closest to what engineers mean is maintainability: “the degree of effectiveness and efficiency with which a product or system can be modified to improve it, correct it or adapt it to changes in environment, and in requirements” (iso25000.com).

It splits maintainability into five sub-characteristics. The model defines them in words, not formulas, so you measure each through proxies:

Sub-characteristic What ISO means Proxies you can measure
Modularity A change to one component has minimal impact on the others Class coupling, files touched per change
Reusability A part can be used in more than one system Duplication
Analysability You can assess the impact of a change, diagnose failures and find the parts to modify Cognitive complexity, maintainability index
Modifiability The code can be changed without introducing defects or degrading quality Change fail rate, defect density, churn
Testability Test criteria can be set and tests run to check them Cyclomatic complexity, test coverage

Reliability is a separate characteristic in the same model, and analyzers rate it separately: SonarQube grades reliability by the bugs it finds and security by the vulnerabilities (SonarQube docs).

12 code quality metrics, with formulas and traps

The 12 code quality metrics below fall into four groups: what an analyzer reads in the code, what the tests show, what review catches, and what happens after the code ships. Each misleads in a known way, so the last column matters as much as the formula.

Metric Group How it’s computed The trap
Cyclomatic complexity Code 1 + the number of conditional branches, per function Counts paths, not readability: a flat switch scores as high as nested loops
Cognitive complexity Code +1 for each break in linear flow (if, loop, catch), plus +1 for each level of nesting Says nothing about names or design
Maintainability index Code Visual Studio’s formula from Halstead volume, cyclomatic complexity and lines of code, scaled 0 to 100 Two of its three inputs measure size, and one number hides which input moved
Duplication Code Duplicated lines ÷ lines × 100 Generated code and test fixtures inflate it unless you exclude them
Static analysis issues Code New issues the analyzer or linter raises on a change Untuned rules make noise that people learn to ignore
Technical debt ratio Code Estimated remediation minutes ÷ (30 minutes × lines of code) The minutes are the tool’s estimate, not your team’s
Test coverage Tests Covered lines ÷ executable lines; SonarQube also counts conditions Shows what ran, not what was checked
Code churn Outcome Share of new lines rewritten or deleted within weeks of being written Planned refactoring churns too
Defect density Outcome Confirmed defects ÷ thousand lines of code, per release or quarter Rises when you test harder, which is good news
Change fail rate Outcome Deployments that needed immediate intervention ÷ all deployments Needs incident data your Git host doesn’t have
PR size Review Median lines changed per merged pull request Lockfiles and generated files inflate it
Review findings Review Share of pull requests a reviewer flags with a should-fix issue Moves when the reviewer’s strictness changes

Code metrics are cheap and immediate but only predict trouble. Outcome metrics show the trouble itself, weeks later. Use both.

Code metrics: complexity, duplication and maintainability

Cyclomatic complexity counts the independent paths through a function. Thomas McCabe defined it on the control-flow graph; per module it is edges minus nodes plus 2 (Watson and McCabe, NIST SP 500-235, 1996). SonarQube counts it as “1 + number of conditional branches”. McCabe used 10 as “a reasonable, but not magical, upper limit” (McCabe, IEEE Transactions on Software Engineering, 1976), and the NIST guide adds that “limits as high as 15 have been used successfully as well.”

Cognitive complexity is SonarSource’s answer to what cyclomatic complexity misses. G. Ann Campbell’s white paper says cyclomatic complexity “accurately calculates the minimum number of test cases required to fully cover a method” but is “not a satisfactory measure of understandability” (SonarSource, version 1.7, 2023). In its example, a method with two nested loops and an if and a method with a four-way switch both score 4 on cyclomatic complexity, and 7 and 1 on cognitive complexity, because a switch is read at a glance and nesting is not.

Maintainability index folds several metrics into one number. Visual Studio computes it as:

Maintainability Index = MAX(0,(171 - 5.2 * ln(Halstead Volume) - 0.23 * (Cyclomatic Complexity) - 16.2 * ln(Lines of Code))*100 / 171)

Microsoft rates 20 to 100 green, 10 to 19 yellow and 0 to 9 red, set conservatively so that red means “a high degree of confidence that there was an issue with the code” (Microsoft Learn). Use it to find the worst files, not to compare teams.

Duplication and the technical debt ratio come from the same analyzer. SonarQube’s duplication density is duplicated lines divided by lines, times 100. Its debt ratio divides technical debt, “the sum of the maintainability issue remediation costs”, by the cost to write the code, 30 minutes a line by default, and rates a codebase A at 5% or less, down to E at 50% or more. Many rules behind those issues are code smells with a threshold: a method too long, a block repeated. The ratio sees only what rules can see; how to reduce technical debt covers the rest, like a stalled migration.

Test metrics: what coverage tells you and what it doesn’t

Test coverage is the share of code your tests execute: SonarQube’s line coverage is covered lines divided by executable lines, and its condition coverage asks whether each boolean expression has been both true and false. It doesn’t show whether the tests check anything, since a test that asserts nothing still covers the code it calls. Martin Fowler: “Test coverage is a useful tool for finding untested parts of a codebase”, and it “is of little use as a numeric statement of how good your tests are.” He expects coverage in the upper 80s or 90s from teams that test thoughtfully, and would be “suspicious of anything like 100%” (martinfowler.com, 2012).

So measure coverage on new code and treat a drop as a question for the review. What makes the tests themselves good is in unit testing best practices.

Outcome metrics: change fail rate, defects and churn

Outcome metrics show quality after the code ships: what broke and what had to be redone. They lag, but they are the ones that cost money.

  • Change fail rate. DORA defines it as “the ratio of deployments that require immediate intervention following a deployment,” and pairs it with deployment rework rate, “the ratio of deployments that are unplanned but happen as a result of an incident in production” (dora.dev). Both need incident data. The engineering KPIs post has formulas for the full DORA set.
  • Defect density. Confirmed defects per thousand lines of code, per release. Count only defects found after merge, or it rewards the teams that test least.
  • Code churn. The share of recently written lines rewritten or deleted soon after; GitClear, which sells engineering analytics, tracks it over two weeks. High churn on new code often means the first version was wrong.

PR size and review findings show up earlier, before the merge; our data on them is in the AI section below.

How to measure code quality in 5 steps

1. Pick three to five metrics, from more than one group

A good first set: cognitive complexity and duplication on new code, coverage on new code, change fail rate, and PR size. Each answers a different question, so one can’t hide a problem in another.

2. Record a baseline before you change anything

Run the analyzer on the default branch and pull a month of outcome data before you set a rule, or you won’t know whether the rule helped.

3. Measure new code, not the whole codebase

An old codebase won’t pass a strict gate this quarter, and a gate everyone fails gets switched off. Gate what changed. SonarQube’s built-in “Sonar way” quality gate has four conditions, all on new code: no new issues, all new security hotspots reviewed, new code coverage of at least 80%, and duplication in new code of at most 3% (SonarQube docs).

4. Put the check in CI and the editor

Put each limit where the code is written, so it fails before a reviewer has to say it. A linter can cap complexity per function. ESLint’s complexity rule defaults to 20 (ESLint docs); this sets McCabe’s 10:

// eslint.config.js
export default [
  {
    rules: {
      complexity: ["error", { max: 10 }],
    },
  },
];

On a function with ten if branches, ESLint reports “Function ‘f’ has a complexity of 11. Maximum allowed is 10” and exits with an error, which fails the CI step.

5. Read trends, not snapshots

Chart each metric monthly per repository or service; one reading says little. PR size is the easiest start, because your Git host already has it. This prints the median lines changed and the share of pull requests of 1,000 lines or more (it needs the GitHub CLI and jq; GitHub search returns at most 1,000 results, so run it per month on a busy repository):

gh pr list --repo owner/repo --state merged --limit 1000 \
  --search "merged:>=2026-10-01" \
  --json additions,deletions |
jq '[.[] | .additions + .deletions] | sort
  | {merged: length,
     median_lines: .[(length - 1) / 2 | floor],
     pct_1000_plus: ((map(select(. >= 1000)) | length) / length * 100 | round)}'

Lockfiles and generated files count as changed lines, so exclude dependency bumps. Then ask the people who pay for bad code. Since 2018, Google’s quarterly engineering survey has asked engineers how far they are “hindered by unnecessary complexity and technical debt”, and none of the 117 metrics it tested predicted those answers on its own.

Code quality tools

Code quality tools read the code itself; none of them sees incidents.

Tool What it reports Worth knowing
SonarQube Cyclomatic and cognitive complexity, duplication, coverage, issues, technical debt ratio, A to E ratings Quality gates on new code; the “Sonar way” gate is built in
Qlty Linting, formatting, security, duplication, complexity and coverage Took over Code Climate Quality, whose organizations were migrated to it (Qlty docs); its CLI is free
Codacy Complex, error-prone and unused code, duplication, coverage and security Pitches itself on enforcing “code quality, security and AI coding standards from a single place”
GitHub Code Quality and CodeQL Reliability and maintainability ratings Ratings come from the severity of CodeQL findings on the default branch; code scanning on private repositories needs a GitHub Code Security license (GitHub Docs)
Linters, such as ESLint Rule violations, including per-function complexity limits Run in the editor and in CI, before review
Visual Studio code metrics Maintainability index, cyclomatic complexity, depth of inheritance, class coupling and lines of code Built into Visual Studio, for managed (.NET) code

A code quality dashboard built on these covers only the code half. For delivery, the developer productivity metrics guide compares DORA, SPACE and the DX Core 4, with a GitHub script for PR cycle time.

How to measure the quality of AI-written code

You measure AI-written code with the same metrics, then split them by what wrote each change. The research so far:

  • The code looks better, delivery less stable. Google’s 2024 DORA report estimated that a 25% increase in AI adoption goes with a 3.4% increase in code quality and a 1.8% decrease in code complexity, and with a 7.2% reduction in delivery stability (DORA 2024). The 2025 report, from nearly 5,000 respondents, found AI now improves throughput, but “it still increases delivery instability.” In that survey 59% said AI had improved their code quality, 10% said it had made it worse, and 30% reported little to no trust in the code AI generates (DORA 2025).
  • Less refactoring, more copying. GitClear studied 623 million code changes from 2023 to 2026. Moved code, its marker for refactoring, fell from 21% of changed lines in 2022 to 3.8% so far in 2026, while copy/pasted lines rose from 9.4% in 2022 to 15.7% in the first half of 2026 (GitClear, 2026).

So code metrics alone can look fine while delivery gets less stable: pair them with change fail rate, and watch duplication on new code.

Our own data adds which variable to watch. Every pull request in our two main repositories gets a first pass from IonWarp, our sister product’s AI code reviewer. Across 1,232 reviewed pull requests with a readable first pass, merged from August 12 to October 4, 2026 (release PRs left out; what 866 agent-written pull requests show):

Lines changed PRs Clean Notes only Should-fix flag
Under 100 298 62% 27% 11%
100–299 277 39% 38% 23%
300–999 334 21% 34% 45%
1,000–2,999 185 19% 24% 57%
3,000 and more 138 36% 14% 51%

Above 3,000 lines the rate stops rising, partly because the reviewer reads a capped slice of a very large diff. Matched on repository, engineer and week, pull requests of 1,000 lines or more were flagged 36 points more often than those under 300 lines. The gap between models mostly disappeared under the same matching, so the size of the change predicted findings better than the model that wrote it (which model writes the best code).

Three habits follow:

  • Record which agent and model wrote each pull request, or you can’t split any metric by author. We have the agent write a short block into each pull request description.
  • Compare models within the same weeks. Our reviewer, CI and work all changed during those eight weeks.
  • Count what happens to findings. In the 30 days to October 4, 2026, our coding agents answered 2,273 reviewer findings: they fixed 80%, declined 18% and handed 1.6% to a person. And 86% of the 866 agent-written pull requests touched a test file, against 61% of those merged in the same weeks without the agent’s block.

Code review best practices covers holding agent code to the same review bar, and AI coding analytics tools compares the tools that read agent usage.

Code quality metrics to avoid

The code quality metrics to avoid measure size or activity, or turn into a target:

  • Lines of code and commit counts. They measure how much, not how good, and a coding agent produces both on demand. McCabe made the point in 1976: limiting modules by physical size (IBM’s 50 lines, TRW’s two pages) “is not adequate.”
  • Coverage as a goal. A coverage target gets met with tests that assert little. DORA lists “setting metrics as a goal” among the common pitfalls of its own metrics, citing Goodhart’s law.
  • One composite score as the goal. A maintainability index or a letter grade is a fine alarm, but it hides which input moved.
  • Any metric ranked by engineer. DORA says its metrics “are meant to be applied at the application or service level.” Complexity and coverage describe code, not the person who last touched it.

Zest is ours, and it doesn’t measure code quality: it runs no analyzer, computes no quality score and no DORA metric, and collects no code diffs. It records each engineer’s coding-agent sessions and links each one to the GitHub pull request it led to, so you can see which agents and models wrote the pull requests your quality metrics flag. Keep SonarQube, your linter and your CI for the code itself.

Frequently asked questions

Which three are code quality metrics?

Cyclomatic complexity, test coverage and code duplication: SonarQube defines all three in its metric reference, and each describes the code itself. Lines of code and commit counts are not, because they measure size and activity.

What is a good cyclomatic complexity?

10 or less per function is the classic limit: McCabe called it “a reasonable, but not magical, upper limit” in 1976. NIST’s guide on the metric says limits up to 15 have been used successfully. ESLint’s default limit is 20.

What is a good code coverage percentage?

There is no universal number. SonarQube’s built-in gate asks for 80% on new code, and Martin Fowler expects the upper 80s or 90s from teams that test thoughtfully, but is suspicious of anything like 100%.

How do you track code quality over time?

Gate new code in CI and chart three to five metrics monthly per repository, such as complexity and coverage on new code, PR size and change fail rate. Compare each month with your own baseline, not with another team.

Is AI-generated code lower quality?

The evidence is mixed. In DORA’s 2024 report, more AI adoption went with slightly better code quality and lower delivery stability, and GitClear sees more copied and less refactored code since 2022. In our own pull requests, size predicted review findings far better than the model that wrote the code.

Zest is AI coding analytics for engineering teams: it shows which coding agents, models and skills each engineer uses, what they cost, and which sessions end in merged pull requests. See how Zest works.