- Published on
- · July 10, 2026
Cyclomatic Complexity: What It Is and How to Calculate It
- Blog

- Henrico Piubello
- Henrico Piubello
- IT Specialist - Grupo Voitto
IT Specialist - Grupo Voitto

Cyclomatic complexity is a software metric, created by Thomas J. McCabe in 1976, that counts the number of independent execution paths of a program. It is used to assess the testability and maintainability of code: the more conditionals and loops, the higher the value — and the higher the risk of defects.
- What is cyclomatic complexity?
- How to calculate cyclomatic complexity?
- What is a good cyclomatic complexity value?
- Benefits of measurement for maintenance and testing
- Which tools compute cyclomatic complexity?
- How to reduce cyclomatic complexity in practice
What is cyclomatic complexity?
Cyclomatic complexity is a quantitative metric that represents the number of linearly independent paths a program's execution can take. It was proposed by Thomas J. McCabe in the article "A Complexity Measure" (IEEE Transactions on Software Engineering, 1976) as an objective, measurable way to assess software structural complexity.
The reasoning is direct: every control structure — if, else, while, for, case — creates a possible branch in the program's flow. The more branches, the more distinct paths exist, the more scenarios need to be tested, and the harder it becomes to understand what the code actually does. If you're still consolidating those fundamentals, the CodeCrush guide on programming logic and control structures covers the needed base.
Cyclomatic complexity also sets a floor for test coverage: a function with complexity 7 demands at least 7 test cases to exercise all its independent paths — a central principle of the basis path testing technique, used in white-box testing.
How to calculate cyclomatic complexity?
Cyclomatic complexity is computed over the program's control-flow graph using McCabe's formula: M = E − N + 2P, where E is the number of edges in the graph, N is the number of nodes, and P is the number of connected components (usually 1 for an isolated function).
Day to day, nobody draws the graph by hand. There's an equivalent shortcut:
- Start with the value 1 for the function.
- Add 1 for each
if,else if,while,for, anddo-while. - Add 1 for each
caseof aswitch. - Add 1 for each ternary conditional operator and each short-circuit logical operator (
&&,||) in conditions. - The total is the function's cyclomatic complexity.
A quick example: a function with one if/else and a for loop has complexity 3 (1 base + 1 for the if + 1 for the for). A function with no branches at all — only sequential statements — has complexity 1, the minimum possible.
What is a good cyclomatic complexity value?
The classic limit is 10 per function, proposed by McCabe himself in 1976 and reaffirmed by the NIST (National Institute of Standards and Technology) in publication SP 500-235, "Structured Testing" (Watson & McCabe, 1996), which accepts limits of up to 15 in teams with mature processes and rigorous testing. Modern tools adopt different standards, as the table shows:
| Complexity range | Interpretation | Reference |
|---|---|---|
| 1–10 | Simple code, low risk | McCabe (1976) |
| 11–15 | Acceptable with mature team and tests | NIST SP 500-235 (1996) |
| 16–20 | High; 20 is the ESLint default ceiling | ESLint complexity rule |
| 21–25 | Very high; 25 triggers the CA1502 alert in .NET | Microsoft Learn, CA1502 |
| Above 25 | Critical; refactoring strongly recommended | Microsoft Learn, CA1502 |
Microsoft's documentation sums up the consensus well: "A low cyclomatic complexity generally indicates a method that is easy to understand, test, and maintain". It's worth remembering the limit is an alert, not a law: a large, readable switch can exceed it without posing real risk.
Benefits of measurement for maintenance and testing
Measuring cyclomatic complexity brings concrete benefits across four fronts of the development cycle:
- Risk-point identification: functions with high complexity statistically concentrate more defects; the metric points to where debugging and code review should focus first.
- Test prioritization: the metric's value indicates the minimum number of test cases to cover all paths, guiding the software testing strategy toward the critical areas.
- Cheaper maintenance: low-complexity code is easier to understand, extend, and review, reducing the cost of every change over the system's life.
- Objective refactoring guide: instead of debating style, the team uses a number to decide what to simplify — a pillar of clean code practices.
Cyclomatic complexity works better as a continuous thermometer than as a one-off audit: tracking the value's trend release after release reveals whether the codebase is getting healthier or accumulating technical debt.
Which tools compute cyclomatic complexity?
Static analysis tools compute cyclomatic complexity automatically from the source code, without the developer having to build graphs or count decisions by hand. The most-used options are:
- SonarQube: a multi-language continuous analysis platform that reports complexity per function, file, and project.
- ESLint: the
complexityrule alerts when a JavaScript or TypeScript function exceeds the configured limit (default 20). - PMD: an open-source code analyzer with complexity rules for Java, Apex, and other languages.
- Radon: a Python library that grades functions from A to F according to complexity.
- .NET analyzers: the CA1502 rule measures the metric in C# and Visual Basic with a configurable threshold.
The biggest gain comes from integrating these tools into the workflow: running in the IDE, they give real-time feedback as the code is written; running in the CI/CD pipeline, they block functions above the limit from reaching production.
How to reduce cyclomatic complexity in practice
Reducing cyclomatic complexity means eliminating or isolating decision points, and a few refactoring techniques resolve most cases:
- Extract functions: split a large function into smaller, named functions; each carries part of the decisions and becomes testable in isolation.
- Use early returns: replace nested conditionals with guard clauses (
returnup front), flattening the code structure. - Swap conditionals for polymorphism or maps: chains of
if/elseover a type or category can become object dispatch, a dictionary, or the Strategy pattern. - Simplify boolean expressions: extract compound conditions into variables or functions with descriptive names, reducing chained logical operators.
- Measure before and after: run the analysis tool after each refactor to confirm the value dropped without changing behavior — ideally with a test suite covering the existing paths.
Conclusion
Cyclomatic complexity remains, fifty years after McCabe, one of the best cost-benefit metrics in software engineering: a single number, computed for free by tools you probably already use, points exactly to where the code will hurt first. The practical recommendation is pragmatic — set the NIST limit of 10 as an alert in your linter and CI, treat violations as an invitation to refactor, and reserve exceptions for genuinely readable cases like an extended switch. Those who measure complexity at every delivery are rarely caught off guard by it.
## faq
Frequently asked questions
What is cyclomatic complexity for?
Cyclomatic complexity serves to measure how many independent execution paths exist in a function or program. With that number, teams identify hard-to-test and hard-to-maintain sections, prioritize refactoring, and estimate the minimum number of test cases needed to cover every decision in the code.
What is a good cyclomatic complexity value?
A good value sits between 1 and 10 per function, the limit proposed by McCabe in 1976 and reaffirmed by the NIST in publication SP 500-235, which accepts up to 15 for experienced teams. Tools vary: ESLint adopts 20 as the default, and the .NET CA1502 analyzer warns above 25.
How do you calculate the cyclomatic complexity of a function?
Use the formula M = E − N + 2P over the control-flow graph, where E is the edges, N the nodes, and P the connected components. In practice, just add 1 to the number of decision points: each if, while, for, case, and short-circuit logical operator adds 1 to the total.
Is high cyclomatic complexity always bad?
Not necessarily. A long but readable switch can exceed the limit without being a real problem — Microsoft''s own CA1502 rule documentation cites that case as a candidate for an exception. A high value is an alert to investigate, not an automatic refactoring sentence.
Which tool measures cyclomatic complexity?
SonarQube and PMD analyze projects in multiple languages; ESLint brings the complexity rule for JavaScript and TypeScript; Radon serves Python; and .NET computes the metric with the CA1502 rule. All can run in the editor or in the continuous integration pipeline, flagging functions above the configured limit.
Topics in this article
## continue lendo
Artigos relacionados
Keep browsing
Previous article

Types of Linear Regression: Simple, Multiple, Ridge, and Lasso
Meet the types of linear regression — simple, multiple, polynomial, Ridge, and Lasso — with equations, use cases, and criteria for choosing the right model.
Read moreNext article

Machine Learning fundamentals: concepts and algorithms
Machine Learning is the AI field where algorithms learn patterns from data. See the algorithms, learning types, and evaluation metrics.
Read moreAbout the author



