1. Home
  2. Blog
  3. Software Testing

Software Testing

Defect Density: Formula, Worked Examples and How to Use It

Defect density measures how many confirmed defects a piece of software has relative to its size, usually per thousand lines of code. It is one of the simplest quality metrics and one of the easiest to misuse. We calculate it for a five-module release, compare per KLOC with per function point, add severity weighting and defect removal efficiency, and show three ways the number can lie.

9 min read
Defect density: formula, worked examples and how to use it

Key takeaways

  • Defect density = confirmed defects / size, usually expressed per KLOC (thousand lines of code).
  • Our five-module release had 125 defects in 51 KLOC, so 2.45 defects per KLOC, but the modules ranged from 0.97 to 5.37.
  • Weighting by severity changed the total from 125 to 310 points, or 6.08 per KLOC, which better reflects risk.
  • Padding the same 30 defects from 10 to 15 KLOC “improved” density from 3.0 to 2.0 with no change in quality.

“Is this release better than the last one?” and “Which module needs more testing?” are questions every test lead hears. Defect density gives a quick, numeric answer by normalising the defect count by the size of the code, so a large module and a small module can be compared fairly. Used carefully, it points testing and refactoring effort at the riskiest areas. Used carelessly, it rewards verbose code and punishes the teams that test hardest.

All figures below come from a worked example we calculated in Python 3.13.6. The module data is illustrative, not from a real project, so you can follow every step.

What is defect density?

Defect density is the number of confirmed defects found in a component or release divided by its size. Size is most often measured in lines of code, but function points, story points or requirements can also be used. It is a product metric, describing the software, and works best when measured the same way across releases or modules of the same system.

The defect density formula

Defect density = number of confirmed defects / size

Per KLOC:  defects / (lines of code / 1000)
Example:   25 defects in 10,000 lines = 25 / 10 = 2.5 defects per KLOC

Count only confirmed defects: duplicates, invalid reports and “works as designed” tickets are excluded. Be explicit about what you measure for size, for example non-blank, non-comment lines of production code, and keep it the same every time. A small arithmetic check helps too: one widely shared example online divides 30 defects by 15 KLOC and reports 0.5, when the correct answer is 2.

A worked example: one release, five modules

Module Lines of code Defects Defects per KLOC Escaped to production
Accounts 4,100 22 5.37 3
Payments 7,200 36 5.00 5
Checkout 12,400 31 2.50 2
Search 18,000 27 1.50 1
Reports 9,300 9 0.97 0
Release 51,000 125 2.45 11

The release-level figure, 2.45 defects per KLOC, hides a large spread. Search had the most code but one of the lowest densities. Accounts was the smallest module but had the highest density, more than five times that of Reports.

Ranking modules: where to look first

Sorting by density, as in the table, turns the metric into a to-do list. Accounts and Payments stand out at about 5 per KLOC, and they also had the most defects escape to production (3 and 5). That combination, high density and high escapes, is the strongest signal that a module needs more review, more tests and possibly redesign. It is the kind of evidence risk-based testing uses to decide where to spend effort in the next cycle. Raw counts would have pointed at Payments and Checkout instead, sending effort to Checkout simply because it is big.

Per function point instead of per KLOC

Module Function points Defects per function point
Payments 42 0.86
Accounts 30 0.73
Checkout 61 0.51
Search 55 0.49
Reports 48 0.19

Lines of code depend on language and style, so the same feature can be 200 lines in Python or 800 in Java. Function points measure size by delivered functionality (inputs, outputs, inquiries, files and interfaces), which makes comparisons fairer across languages and teams. Here Payments moved to first place, because it delivers fewer function points per line than Accounts. Function point counting needs trained counters; the values above are illustrative.

Severity-weighted defect density

severity counts: critical 3, major 24, minor 62, trivial 36   (125 total)
weights:         critical 10, major 5, minor 2, trivial 1
weighted defects = 3x10 + 24x5 + 62x2 + 36x1 = 310
weighted density = 310 / 51 KLOC = 6.08 per KLOC

A module with ten typos in labels and a module with one data-loss bug are not equally risky, but plain density treats them the same. Weighting each defect by severity gives a figure closer to business impact. Agree the weights with your team and keep them stable, or comparisons over time mean nothing. Severity definitions are part of the bug life cycle and should be applied consistently during triage.

Defect removal efficiency: the companion metric

found before release: 125   escaped to production: 11
DRE = 125 / (125 + 11) = 91.9 percent

Density alone cannot tell good testing from good code. A module with few defects might be well built, or barely tested. Defect removal efficiency (DRE) measures how many defects testing caught before release. Here 91.9 percent were found in house and 11 reached users. Track density and DRE together: rising density with high DRE usually means testing is getting better at finding problems, while low density with low DRE means problems are slipping through.

What is a good defect density?

Published benchmarks vary widely. Some sources call about 1 defect per KLOC good quality, safety-critical industries aim for 0.1 to 0.5, and others quote different scales altogether. The numbers depend on what counts as a defect, when counting stops (end of testing or a year after release), the language and the domain. Treat external benchmarks as rough context. The most useful comparison is with your own previous releases and between modules of the same product, measured the same way.

Three ways defect density lies

30 defects in 10 KLOC         = 3.0 per KLOC
same code padded to 15 KLOC   = 2.0 per KLOC   (looks better, is not)
verbose rewrite at 20 KLOC    = 1.5 per KLOC
  1. More code looks better. The same 30 defects in padded or verbose code produce a lower density. Refactoring that removes duplicate code can make density look worse while the product improves. Never use density to judge individual developers.
  2. Better testing looks worse. A team that adds exploratory testing or mutation testing finds more defects, so its density rises. If people are rewarded for low density, they stop reporting.
  3. Timing changes the answer. Density measured at the end of system testing is not comparable with density measured a year after release, when users have found more. Fix the measurement window.

What counts as a defect?

Decide and document it before you start: include defects from code review? From unit tests that developers fix immediately? Only tester-reported bugs in the tracker? Most teams count confirmed defects logged in the tracker from system testing onwards, plus production defects. Exclude duplicates, environment problems and change requests. Whatever you choose, apply it to every module and release, or the comparisons are meaningless.

Using defect density well

  • Compare like with like: modules of the same product, or releases of the same team, with the same counting rules.
  • Look at trends, not single values. A module whose density rises for three releases is a warning even if the value is still “average”.
  • Pair it with escapes and DRE so that good testing is never punished.
  • Use it to plan, for example more regression coverage for high-density modules in the regression checklist, or extra time in the test estimate.
  • Never use it as a target for individuals or teams. Once a metric becomes a target, people optimise the number instead of the quality.

Tracking defect density

You need two data sources: defect counts per module from your tracker (tag each bug with a component field), and size per module from a line counter such as cloc or your static analysis tool. A short script or spreadsheet joins them each release. Dashboards in tools like SonarQube report related figures, but check exactly what they count. Defects found early are far cheaper to fix, which is the point of shift-left testing; density by phase shows whether that is working.

Final thoughts

Defect density is a simple ratio that becomes useful when you apply it with discipline: confirmed defects only, a consistent size measure, a fixed measurement window and comparisons within your own product. In our example it pointed straight at Accounts and Payments, which also leaked the most bugs to production. Add severity weighting and DRE, watch trends rather than single numbers, and never turn it into a target, and it will guide your testing effort instead of distorting it.

Frequently asked questions

How do you calculate defect density?

Divide the number of confirmed defects by the size of the software. Per KLOC, that is defects divided by lines of code divided by 1000. For example, 25 defects in 10,000 lines is 2.5 defects per KLOC.

What is a good defect density?

There is no universal value. Around one defect per KLOC is often quoted as good, and safety-critical systems aim much lower, but comparing with your own previous releases is far more meaningful.

What is KLOC?

KLOC means thousand lines of code. A module with 7,200 lines is 7.2 KLOC, so 36 defects in it is a density of 5 defects per KLOC.

What is the difference between defect density and defect removal efficiency?

Defect density relates defects to code size. Defect removal efficiency is the share of all defects that testing found before release, such as 125 of 136, or 91.9 percent.

Why can defect density be misleading?

It falls when code gets longer, rises when testing improves, and changes with the measurement window. Use it to compare modules measured the same way, never to rate people.

Keep learning

Work with Stack Quora

Need help with testing, WordPress or SEO?

We help teams ship better software and grow their sites. Tell us what you are working on and we will suggest a clear next step.

Keep reading

More guides on testing, AI & modern development

Enjoyed this article? Pick a topic and jump straight into our newest tutorials.

Artificial Intelligence

Confusion Matrix Explained: Precision, Recall, F1 and Thresholds in Python

Confusion matrix explained with Python: TP, FP, FN, TN, precision, recall, F1, the accuracy trap, threshold choice by cost and…

Read article →
Software Development

API Pagination: Offset vs Cursor vs Keyset, Tested on 1 Million Rows

API pagination explained: offset vs keyset and cursor pagination timed on 1 million rows, duplicates when data changes, the ties…

Read article →
DevOps

Git Submodule Explained: Add, Clone, Update and Remove Safely

Git submodule explained: add, clone, update –init, update –remote, the detached HEAD trap, foreach and clean removal, tested step by…

Read article →
Test Automation

Pytest tmp path Explained: tmp_path, tmp_path_factory and Temp Files

Pytest tmp_path explained: per-test temporary folders, tmp_path_factory for shared files, monkeypatch.chdir, legacy tmpdir, retention and basetemp.

Read article →
Software Testing

Test Case Prioritization: 6 Techniques Compared With APFD

Test case prioritization compared: risk, coverage, cost, history and random orders scored with APFD and time to find all faults…

Read article →
Databases & SQL

Full Text Search in SQL: FTS5, Ranking, Phrases and Speed

Full text search in SQL with SQLite FTS5: MATCH queries, phrases, prefixes, NEAR, stemming, BM25 ranking, snippets, two gotchas and…

Read article →
Databases & SQL

Generated Columns in SQL: Virtual vs Stored, Indexes and Limits

Generated columns in SQL explained: virtual vs stored, automatic updates, write errors, storage cost, indexing, JSON fields and support in…

Read article →
Software Development

Object Freeze in JavaScript: Shallow vs Deep, Seal and const

Object freeze in JavaScript explained: freeze vs seal vs const, strict mode errors, shallow vs deep freeze, frozen arrays, Map…

Read article →
Software Development

Python hashlib: SHA-256, File Hashes, HMAC and Password Hashing

Python hashlib explained: SHA-256 for strings and files, algorithm speeds, why passwords need PBKDF2 or scrypt, safe verification and HMAC…

Read article →
Software Development

Python UUID Explained: uuid1, uuid4, uuid5, uuid7 and Database Keys

Python UUID explained: uuid4, uuid5, uuid1 privacy, time-ordered uuid7, parsing, storage formats and UUIDs as database keys, tested on Python…

Read article →
Artificial Intelligence

Random Forest in Python: Bagging, Feature Sampling and OOB From Scratch

Random forest in Python from scratch: bootstrap sampling, feature sampling, number of trees, out-of-bag evaluation and impurity vs permutation importance.

Read article →
Software Development

MIME Types Explained: Content-Type, nosniff and a Common Types List

MIME types explained and tested in a browser: Content-Type, nosniff, scripts and stylesheets with wrong types, a common MIME types…

Read article →
DevOps

Git Clean Explained: Remove Untracked Files Without Regret

Git clean explained with dry runs: -n, -f, -d, -x, -X, exclusions, paths, nested repositories and interactive mode, plus a…

Read article →
Test Automation

Pytest approx: Comparing Floats With rel, abs and Collections

Pytest approx explained: default tolerances, the near-zero trap, rel and abs, lists and dicts, NaN, NumPy, and how it differs…

Read article →
Software Testing

Accessibility Testing: WCAG Checklist, Automated Tools and Manual Checks

Accessibility testing explained: WCAG basics, an axe-core scan of a broken and a fixed page, what automation missed, contrast checks…

Read article →
Databases & SQL

SQL UNPIVOT: Turn Columns Into Rows, 4 Ways Tested

SQL UNPIVOT explained: turn columns into rows with UNION ALL, CROSS JOIN with CASE, JSON functions or native UNPIVOT, with…

Read article →
Software Development

Intl NumberFormat in JavaScript: Currency, Compact, Percent and Units

Intl.NumberFormat in JavaScript: locales, currency, compact notation, percent, units, rounding, formatToParts, the non-breaking space trap and formatter reuse.

Read article →
Databases & SQL

SQL EXPLAIN Plan: How to Read Query Plans and Fix Slow Queries

SQL EXPLAIN plan explained: read scans, index searches, covering indexes and temporary sorts, with before and after timings for five…

Read article →
Artificial Intelligence

Decision Tree in Python: Gini, Entropy and Overfitting From Scratch

Decision tree in Python from scratch: Gini impurity, entropy, information gain, best splits, readable rules, and how depth and leaf…

Read article →
DevOps

Git Blame Explained: Find Who Changed a Line, and Why

Git blame explained with a real repository: ignore whitespace, line ranges and functions, ignore-revs files for formatting commits, moved code…

Read article →
Test Automation

Pytest Benchmark: Measure Speed and Catch Performance Regressions

Pytest benchmark tutorial: the benchmark fixture, reading results, parametrized and pedantic benchmarks, saving baselines and failing the build on regressions.

Read article →
Software Testing

Defect Density: Formula, Worked Examples and How to Use It

Defect density explained: the formula, a five-module worked example, per KLOC vs per function point, severity weighting, defect removal efficiency…

Read article →
Databases & SQL

Case Insensitive Search in SQL: LOWER, LIKE, COLLATE and Indexes

Case insensitive search in SQL: LOWER, LIKE, COLLATE NOCASE and expression indexes compared with query plans, plus accented letters and…

Read article →
Databases & SQL

ON DELETE CASCADE in SQL: CASCADE vs SET NULL vs RESTRICT

ON DELETE CASCADE in SQL tested: CASCADE vs SET NULL vs RESTRICT, multi-level cascades, the SQLite foreign key pragma, row…

Read article →
Artificial Intelligence

Logistic Regression in Python: Sigmoid, Log Loss and Gradient Descent From Scratch

Logistic regression in Python from scratch: sigmoid, log loss, gradient descent, odds ratios, thresholds, sigmoid overflow and separable data, tested…

Read article →
DevOps

Git Worktree Explained: Work on Two Branches at Once

Git worktree explained: add, list, remove, prune, lock and detached worktrees, a hotfix workflow, and the errors you will hit,…

Read article →
Test Automation

Pytest ini Explained: addopts, markers, testpaths and Precedence

Pytest ini explained: testpaths, addopts, strict markers, xfail_strict, filterwarnings, minversion, config file precedence and command-line overrides, tested.

Read article →
Software Testing

Test Estimation Techniques: WBS, Three Point PERT and Monte Carlo

Test estimation techniques worked through: WBS, three point PERT, total uncertainty, a Monte Carlo check, percentage rules and Wideband Delphi.

Read article →
Artificial Intelligence

Linear Regression in Python: Least Squares From Scratch, With R Squared

Linear regression in Python from scratch: closed form, NumPy least squares and gradient descent, R squared, RMSE, outliers and curved…

Read article →
DevOps

Git Remote Explained: Add, Set-URL, Rename, Remove and Push URLs

Git remote explained: add, set-url, separate push URLs, rename, remove and prune, plus how to avoid leaking tokens in remote…

Read article →
Test Automation

Pytest Mock: mocker.patch, spy, side_effect and autospec Explained

Pytest mock explained: mocker.patch, return_value, side_effect, spy, autospec and PropertyMock, with tested examples for APIs, clocks and retries.

Read article →
Software Testing

System Testing Explained: Types, Process and a Real End-to-End Example

System testing explained: types, entry and exit criteria, the process, and a real end-to-end test suite run against a small…

Read article →
Artificial Intelligence

Naive Bayes Classifier Explained: Build a Spam Filter in Python

Naive Bayes classifier explained by building a spam filter in Python: Bayes rule, the naive assumption, Laplace smoothing, log probabilities…

Read article →
DevOps

Git Branch Explained: Create, Switch, Rename, Delete and Recover

Git branch explained with tested commands: list, create, switch, rename, delete, merged checks, recovering deleted branches, remote tracking and naming.

Read article →
Test Automation

Pytest raises: Testing Exceptions, match and excinfo

Pytest raises explained with tested examples: match regexes, excinfo, custom and chained exceptions, parametrized error cases, pytest.warns and common mistakes.

Read article →
Software Testing

Non Functional Testing: Types, Metrics and a Real Load Test

Non functional testing explained: 10 key types, measurable requirements, latency percentiles and what a small real load test revealed about…

Read article →