Skip to content

Code Complexity: Cyclomatic vs Cognitive vs Change

Compare cyclomatic and cognitive code complexity with change risk. Check corrected examples, understand each measure’s limits and target refactoring effort.

7 min read
Illustrative physical mechanism with three clearly different forms of complexity: a branching linkage, a tightly nested gear assembly, and a modular replaceable junction, arranged in one coherent wide still life.
On this page

I need to tell you something about cyclomatic complexity: it's lying to you. Not maliciously. It's answering a question you didn't ask.

Cyclomatic complexity was designed in 1976 by Thomas McCabe to estimate the number of test cases needed to cover a function. The count depends on the language and analyser. Branches and short-circuit operators can add paths, while a plain else does not independently add another decision. It's a testing metric masquerading as a readability metric, and the entire industry has been treating them as the same thing for decades.

I've seen functions with a cyclomatic complexity of 4 that took me 20 minutes to understand, and functions with a cyclomatic complexity of 15 that I grasped in 30 seconds. The number wasn't wrong. It was measuring the wrong thing.

The code intelligence guide places complexity alongside other evidence about a codebase. Compare each measure with the question you need it to answer.

Cyclomatic Complexity: The OG

Three assessment questions The change-risk formula in the article is a proposed local heuristic. Cyclomatic Independent paths Testing structure Cognitive Flow breaks and nesting Understandability proxy Change risk Dependencies and tests History and contributors
Figure 1. Use each measure for the question its definition addresses.

Cyclomatic complexity (CC) counts the number of linearly independent paths through a function. In practice, it's the number of decision points plus 1.[1]

typescript
// Cyclomatic complexity: 5
function processOrder(order: Order): Result {
  if (!order.items.length) return { status: 'empty' };        // +1
  if (!order.customer) return { status: 'no_customer' };      // +1

  let total = 0;
  for (const item of order.items) {                           // +1
    if (item.discount) {                                       // +1
      total += item.price * (1 - item.discount);
    } else {
      total += item.price;
    }
  }

  return { status: 'ok', total };
}

A CC of 5 identifies five independent control-flow paths under this counting model. It does not establish a minimum of five test cases for branch coverage.

CC doesn't tell you: how hard this function is to understand.

When CC is useful:

  • Estimating test effort
  • Setting a ceiling for function complexity (I use 15 as a hard limit, 10 as a warning)
  • Identifying functions that need refactoring based on testability

When CC misleads:

  • A switch statement with 20 simple cases has CC of 21, but it's trivially readable
  • Nested conditionals and flat conditionals score the same, despite wildly different cognitive loads
  • CC treats all decision points as equal, but an if (x != null) is not as complex as an if (a && (b || c) && !d)

Cognitive Complexity: The Modern Alternative

Equivalent validation examples Both return the same errors for the optional fields. Nested conditions Name check then length Email check then format Cyclomatic 5; cognitive 6 Flat conditions Name && length check Email && format check Cyclomatic 5; cognitive 4
Figure 2. Compare equivalent behaviour before interpreting a lower complexity score.

Cognitive complexity was introduced by SonarSource (the company behind SonarQube) in 2017 specifically to measure how hard code is to understand. It uses three rules:[2]

  1. Increment for breaks in linear flow: if, else, for, while, catch, switch, sequences of logical operators
  2. Increment for nesting: Each level of nesting adds a penalty
  3. Ignore structures that don't impact readability: Null-coalescing, early returns, method extraction

This nesting penalty is the key insight. Compare these two functions:

typescript
// Cyclomatic complexity: 5
// Cognitive complexity: 6
function validateA(user: User): string[] {
  const errors = [];
  if (user.name) {                              // +1
    if (user.name.length < 2) {                 // +2 (nesting penalty)
      errors.push('Name too short');
    }
  }
  if (user.email) {                             // +1
    if (!user.email.includes('@')) {            // +2 (nesting penalty)
      errors.push('Invalid email');
    }
  }
  return errors;
}

// Cyclomatic complexity: 5 (two ifs and two && operators)
// Cognitive complexity: 4 (two ifs and two logical sequences)
function validateB(user: User): string[] {
  const errors = [];
  if (user.name && user.name.length < 2) {
    errors.push('Name too short');
  }
  if (user.email && !user.email.includes('@')) {
    errors.push('Invalid email');
  }
  return errors;
}

Both functions have cyclomatic complexity 5 under the stated JavaScript counting rules. The flat version preserves the original behaviour while reducing the nesting contribution to cognitive complexity from 6 to 4. Inspect the implementation as well as the score when assessing readability.

When cognitive complexity is useful:

  • Measuring readability and understandability
  • Identifying functions that are hard for new team members to grasp
  • Guiding refactoring decisions toward genuinely simpler code, not just fewer test paths

When cognitive complexity falls short:

  • It doesn't account for domain complexity. A function that implements a complex business rule will have high cognitive complexity even if the code is the clearest possible expression of that rule.
  • It's language-specific. The SonarSource implementation handles Java and TypeScript well but may not account for language-specific idioms in other ecosystems.

Change Complexity: The Missing Metric

Here's the one nobody talks about, and it's the most useful in practice.

Assess change risk by tracing what a modification could affect. Use dependency mapping for the structural relationships and hotspot analysis to identify frequently changed areas.

Change complexity isn't a formal metric with a formula. It's a composite score derived from:

  1. Coupling breadth: How many other files/modules are affected when this code changes?
  2. Test coverage: What percentage of this code's behavior is verified by tests?
  3. Historical defect rate: How often do changes to this file introduce bugs?
  4. Author diversity: How many different developers have successfully modified this code?

I calculate change complexity with a formula like this:

Change Complexity = (Coupling Breadth * 0.3) +
                    ((100 - Test Coverage) * 0.3) +
                    (Defect Rate * 0.25) +
                    ((1 / Author Count) * 0.15)

This is a proposed local heuristic. Define the input scales, handle an author count of zero and validate the weights before comparing scores. The principle is that a function might be easy to read (low cognitive complexity) and easy to test (low cyclomatic complexity) but extremely dangerous to change because it's coupled to 15 other modules, has 40% test coverage, and only one person has ever modified it successfully.

A real example

We had a billing calculation function at a previous company. Cyclomatic complexity: 8. Cognitive complexity: 6. By any standard metric, it was fine. Clean code.

But its change complexity was off the charts. It was imported by 23 other modules. It had no integration tests (only unit tests with mocked dependencies). And in the last 12 months, 4 out of 6 changes to it had caused production incidents.

The function was easy to read and easy to test in isolation. It was nearly impossible to change safely. Only change complexity captured that reality.

The Framework: CCC Assessment

When evaluating a module's complexity, I run all three analyses:

Cyclomatic (Can I test it?): If CC > 15, the function has too many branches. Extract some paths into separate functions.

Cognitive (Can I read it?): If cognitive complexity > 10, the function is hard to understand. Reduce nesting, use early returns, extract sub-expressions into named variables.

Change (Can I modify it safely?): If change complexity is high, the function is risky regardless of how clean it looks. Increase test coverage, reduce coupling, spread knowledge across the team.

The three metrics together give you a complete picture. Any one alone is misleading.

The Contrarian Take: Complex Code Isn't the Problem. Changing Complex Code Is.

Teams spend enormous effort reducing complexity scores. They refactor, they extract, they simplify. And that's often the right call. But I've seen teams burn weeks refactoring code that doesn't change.

If a function has a cyclomatic complexity of 35 but hasn't been modified in 2 years and has full test coverage, leave it alone. Your refactoring effort is better spent on the function with a complexity of 12 that changes every sprint and keeps breaking things.[3]

Complexity itself doesn't cause bugs. Changing complexity causes bugs. Focus your refactoring budget on the intersection of complexity and churn. That's where the bugs live.

Tooling in 2026

  • ESLint complexity rule: Cyclomatic complexity for JavaScript/TypeScript
  • SonarQube / SonarCloud: Both cyclomatic and cognitive complexity with trend tracking
  • Qlty: Code smells, metrics and coverage tooling from the makers of Code Climate
  • Custom scripts + git log: Change complexity (you'll need to build this yourself, but it's worth it)

Qlty documents code metrics and coverage. Inspect the definitions of the measures your tool reports, then combine them with the local evidence needed to assess a proposed change.[4]

Frequently asked questions

Does cyclomatic complexity tell me how many branch tests I need?

Cyclomatic complexity counts independent control-flow paths under the analyser’s rules. It does not give a universal minimum number of test cases for branch coverage, since a test can exercise several branches.

Why can nesting raise cognitive complexity?

Cognitive complexity adds cost for breaks in the reading flow and for some nested structures. Compare equivalent implementations and inspect the rule details, since a shorter version with different behaviour is not a valid refactor.

Is change complexity a standardised score?

The article proposes a composite assessment of change risk. Its weights and thresholds need validation for the codebase, and the input scales and author-count handling must be defined before comparing numerical scores.

Which code should we refactor first?

Inspect areas where difficult code also changes frequently or has costly failures. Combine structural measures with tests and historical evidence, then verify the dependency and behaviour risks of the proposed change.

Sources

  1. [1]complexity - ESLint - Pluggable JavaScript Linter · ESLint
  2. [2]Cognitive Complexity - a new way of measuring understandability · SonarSource
  3. [3]Technical Debt — CodeScene 1 Documentation · CodeScene
  4. [4]What is Qlty? - Qlty Docs · Qlty

Checked against these sources on

Related Articles