Cognitive Complexity
SonarSource's cognitive complexity per function, which penalizes deeply nested control flow more than cyclomatic complexity does; a file is graded by its most complex function.
Cognitive complexity, introduced by SonarSource, addresses cyclomatic complexity's main shortcoming: it treats all branches as equally costly. In reality, a flat switch with 10 cases is easier to read than a triply-nested if ladder with the same number of branches.
The metric is scored per function. Each if, loop, switch, catch and ternary adds 1 plus its nesting depth; each run of like boolean operators and each jump to a label adds 1. A boolean expression is read left to right through parentheses only, so a || b && c || d is three runs, and a condition inside a call argument, a callback or a ternary branch is counted on its own. A function nested inside another one and bound to a name is measured on its own; an inline callback counts toward the function that contains it, one nesting level deeper. Recursion and a plain else are not scored (a documented subset of the methodology).
The limits (15 warning, 30 critical) are compared with the most complex function unit of the file. The file total is reported as a size measure and is never compared with them.
Severity guide
- info
- Every function is within the acceptable range. No action required.
- warning
- A function scores above 15, or nesting somewhere in the file is deeper than 4. Refactoring is recommended to keep the code readable as it grows.
- critical
- A function scores above 30. Most developers will struggle to read it without extensive study.
Examples
Before
function process(items) {
if (items) {
if (items.length > 0) {
for (const item of items) {
if (item.active) {
if (item.type === 'a') {
// do work
}
}
}
}
}
}After
function process(items) {
if (!items || items.length === 0) return;
for (const item of items) {
if (!item.active || item.type !== 'a') continue;
doWork(item);
}
}Guard clauses (early returns and `continue` statements) flatten the nesting hierarchy without changing behavior. Cognitive complexity drops from 15 to 6.
Remediation
Reduce nesting via guard clauses and early returns; extract deeply nested blocks into named helpers.
- Identify the deepest nesting point and rewrite the outer condition to return or
continueearly instead of nesting the happy path. - Extract the body of any deeply nested loop or conditional into a named function. The function name documents the intent, and the call site loses an indent level.
- Break long boolean chains (
x && y && z && (a || b)) into named predicates that read like sentences. - Avoid nesting
try/catchblocks unless the inner catch handles something meaningfully different from the outer one.