Cognitive complexity is a code quality metric that measures how difficult a function or method is for a human to read and understand. It was developed by G. Ann Campbell at SonarSource in 2016 as a more accurate alternative to cyclomatic complexity, which counts execution paths but ignores how a developer actually experiences reading nested, branching code.
The score rises with each structural element that interrupts the natural reading flow: loops, conditionals, recursion, deeply nested logic. A flat function with a single loop might score 1 or 2. A function with four levels of nested conditionals can reach 30 or higher.
Cognitive Complexity is calculated by SonarSource's algorithm, which assigns increment values to structural control flow elements and applies additional penalties for nesting depth.
The core formula is:
Cognitive Complexity = Base increments + Nesting penalties
Each loop, conditional, or switch statement adds 1. Each level of nesting inside those structures adds an additional 1 per level. Recursion adds 1. Jumps in control flow (break with a label, goto) add 1. The result is a single integer score per function.
Data sources: static analysis on the raw source code. SonarCloud, SonarQube, and integrated IDE plugins (VS Code, IntelliJ) can report it per function. Most CI pipelines can be configured to fail builds when a function breaches a threshold.
Cyclomatic complexity counts the number of linearly independent paths through a function. Cognitive complexity counts the mental overhead of following those paths. A function with three nested if-statements can have the same cyclomatic score as one with three sequential if-statements, even though the nested version is much harder to understand. Cognitive complexity penalizes nesting explicitly, which is why SonarSource built it as a replacement for code review threshold enforcement.
High cognitive complexity is a delivery risk. PR review times lengthen when reviewers have to trace deep conditional logic before they can verify correctness. Bug rates rise in functions that are hard to reason about during review. Refactoring becomes risky because the blast radius of a change is hard to predict. At MoveInSync, Hivel identified that large, complex PRs were extending review times by 37% before teams addressed the problem. Engineering leaders who track cognitive complexity can see code quality degrading before it becomes a production incident. Platforms like Hivel surface cognitive complexity alongside PR cycle time and change failure rate so leaders can see system-level patterns at hivel.ai/use-cases/code-quality, not isolated data points.
See how Hivel tracks cognitive complexity across your engineering org →



We'll show you exactly how AI is impacting your speed and code quality.



See exactly how AI-assisted code is impacting your delivery speed and code quality, before you commit to anything.
Trusted by 1000+ teams