Cyclomatic vs Cognitive Complexity: What Each Metric Tells You
Cyclomatic vs cognitive complexity, explained with one code example: what each metric counts, where they disagree and which thresholds to enforce in CI.
In this article:
- Two metrics, two different questions
- How each metric is calculated
- A code example: same cyclomatic score, different reading effort
- Thresholds that work in practice
- How to use both metrics in your pipeline
- Conclusion
Most static analysis tools now report two complexity numbers per function, and teams often treat them as interchangeable. They are not. The debate of cyclomatic vs cognitive complexity is really a question about what you want to protect: your test suite, or the engineer who has to read the code next quarter.
This guide is a practical comparison. If you need the fundamentals of McCabe’s metric first, start with our article on cyclomatic complexity explained. Here we focus on how the two metrics differ, a small code example where they disagree, and the thresholds we recommend enforcing.
Two metrics, two different questions
Cyclomatic complexity answers a structural question: how many independent paths run through this function? It was designed by Thomas McCabe in 1976 as a graph-theory measure, and it maps closely to testing effort. A function with a score of 8 has eight independent paths, which is a good estimate of how many test cases you need to exercise every branch.
Cognitive complexity answers a human question: how hard is this function to understand? It was introduced by G. Ann Campbell at SonarSource as a deliberate alternative, because cyclomatic scores often rank code in an order that does not match what developers experience. A flat switch with three cases and three loops nested inside each other have the same cyclomatic score, yet nobody finds them equally easy to read.
The difference matters because understandability is where maintenance time goes. In Stripe’s developer survey, respondents reported spending on average 17.3 hours of a 41.1-hour week on maintenance work such as debugging, refactoring and modifying existing code (Stripe, The Developer Coefficient). Much of that time is spent reading code before changing it, and cognitive complexity is the metric that targets reading.
| Cyclomatic complexity | Cognitive complexity | |
|---|---|---|
| Question it answers | How many paths must be tested? | How hard is this to understand? |
| Origin | McCabe, 1976 | SonarSource white paper (G. Ann Campbell) |
| Nesting | Ignored | Penalised, more with each level |
switch with many cases | Each case adds one | The whole switch adds one |
| Best use | Test planning, branch coverage | Code review, refactoring priority |
| Typical tools | ESLint complexity, radon, PMD, SonarQube | SonarQube, SonarLint, eslint-plugin-sonarjs |
How each metric is calculated
Cyclomatic complexity: counting paths
The formal definition works on the control flow graph: edges minus nodes plus two, for a single function. In practice every tool uses the shortcut: start at 1 and add 1 for each decision point. Decision points are if, else if, each case label, for, while, do, catch and the ternary operator.
Most tools also count each && and || in a condition, because each one creates an extra path. The tools differ slightly here, so a function can score 6 in one tool and 7 in another. Compare numbers from the same tool over time rather than across tools.
Cognitive complexity: counting mental effort
Cognitive complexity follows three rules, described in the SonarSource white paper:
- Ignore shorthand. Structures that let a reader take in several statements at once do not add anything. A method call, a null-coalescing operator or an early
returndoes not make code harder to follow. - Add one for each break in linear flow.
if,else if,else,switch, loops,catch, the ternary operator, jumps to labels, recursion and each sequence of like logical operators add 1 (a && b && cadds 1,a && b || cadds 2). Aswitchadds 1 in total, not 1 per case. - Add more for nesting. When a flow-breaking structure sits inside another one, it receives an extra increment equal to its nesting depth. An
ifinside a loop inside anifcosts 3, not 1.
The third rule is the heart of the metric. Nesting forces the reader to keep every enclosing condition in mind at the same time, and the score grows with exactly that burden.
A code example: same cyclomatic score, different reading effort
Here are two small TypeScript functions. Both have a cyclomatic complexity of 4.
The first maps a region to a shipping label:
function shippingLabel(region: string): string {
switch (region) { // cognitive +1 (whole switch)
case "EU": return "Standard EU";
case "UK": return "UK customs";
case "US": return "International";
default: return "Manual review";
}
}
Cyclomatic: three case labels plus one, so 4. Cognitive: 1. Anyone can read it in seconds, and the cognitive score reflects that.
The second applies a sale discount:
function applyDiscount(order: Order): number {
let total = order.subtotal;
if (order.customer) { // cognitive +1
for (const item of order.items) { // cognitive +2 (nesting 1)
if (item.onSale) { // cognitive +3 (nesting 2)
total -= item.price * 0.1;
}
}
}
return total;
}
Cyclomatic: three decision points plus one, so 4, the same as the switch. Cognitive: 1 + 2 + 3 = 6. The reader has to hold “customer exists” and “inside the loop” in mind before reaching the line that actually changes the total. Cyclomatic complexity says the two functions are equivalent. Cognitive complexity scores the second one six times higher, which matches what any reviewer feels.
Now the same logic after two standard refactorings, a guard clause and a collection pipeline (both covered in our guide to refactoring techniques):
function applyDiscount(order: Order): number {
if (!order.customer) return order.subtotal; // cognitive +1
return order.items
.filter((item) => item.onSale)
.reduce((total, item) => total - item.price * 0.1, order.subtotal);
}
Cognitive complexity drops from 6 to 1 and the outer function’s cyclomatic complexity drops from 4 to 2. The behaviour is identical, which you should confirm with tests before merging. On legacy code without tests, write characterization tests first.
The lesson generalises. A long, flat switch is rarely the problem, even if its cyclomatic score is high. Deep nesting is almost always the problem, even when the cyclomatic score looks acceptable.
Thresholds that work in practice
There is no universal limit, but there are well-established defaults. McCabe proposed 10 as the upper limit for cyclomatic complexity per function. ESLint’s complexity rule defaults to 20. SonarQube’s rule for cognitive complexity flags functions above 15 by default.
These are the working bands we use when we review a codebase. Apply them per function, not per file or per module.
| Score per function | Cyclomatic complexity | Cognitive complexity |
|---|---|---|
| Comfortable | 1 to 10 | 0 to 7 |
| Acceptable, watch it | 11 to 15 | 8 to 15 |
| Refactor before the next change | 16 to 25 | 16 to 25 |
| Priority for remediation | above 25 | above 25 |
Three practical notes on complexity thresholds:
- Rank, do not just filter. A list of functions above the limit is less useful than the same list sorted by score multiplied by change frequency. Complex code nobody touches is low risk. Complex code changed every week is where incidents start.
- Treat a high cyclomatic score with low cognitive complexity as a testing task. A large flat
switchor a validation table may be easy to read but still needs one test per branch. - Treat high cognitive complexity as a refactoring task. It points to nesting, mixed boolean logic and tangled control flow, which slow down every review and every change.
How to use both metrics in your pipeline
Code quality metrics only change behaviour when they are part of the daily workflow. This is the setup we recommend:
- Enable both metrics in your static code analysis tool, at function level.
- Gate new and changed code only. A rule that fails the build on legacy code nobody is touching gets disabled within a week.
- Set the gate on cognitive complexity at 15 for new code, and report cyclomatic complexity as information for test planning.
- Show the score in the pull request, so the reviewer sees the delta while the context is fresh.
- Review the top 20 functions by cognitive complexity times change frequency once per quarter, and schedule the worst ones as refactoring work.
- Track the trend, not the absolute number. A median that rises sprint after sprint is the early signal of accumulating debt.
Both metrics belong in a broader picture alongside test coverage, duplication, coupling and delivery metrics. Our guide on how to measure technical debt shows how complexity fits into a full measurement model.
One caveat: neither metric sees architecture. A function with a cognitive score of 2 can still call six services in the wrong order. Complexity scores tell you where code is hard to read and test. They do not tell you whether the design is right.
Conclusion
The answer to cyclomatic vs cognitive complexity is not either-or. Cyclomatic complexity tells you how much testing a function needs. Cognitive complexity tells you how much effort it costs to understand and change it. When the two disagree, cognitive complexity is usually the better guide for refactoring priority, and cyclomatic complexity the better guide for test planning.
Start by enabling both, gating cognitive complexity on new code, and ranking existing hotspots by score and change frequency. That gives you a short, defensible list of where to refactor first, without stopping feature work.
If you want an independent view of where complexity is really costing your team, our code audit measures both metrics across your codebase, ranks the hotspots against change history and turns the findings into a prioritised, incremental remediation plan.