← Home ← Codex ← DEBT ← Engine
Browse by Category
+ added · updated 7d
← Back to glossary

Cognitive Complexity

Code Quality Intermediate
debt(d3/e5/b5/t5)
d3 Detectability Operational debt — how invisible misuse is to your safety net

Closest to 'default linter catches the common case' (d3). Tools like phpmd, phpcs, sonarqube, and phpstan (all listed in detection_hints.tools) can calculate cognitive complexity automatically with standard rulesets. SonarQube specifically pioneered this metric. Detection is straightforward and commonly configured in CI pipelines.

e5 Effort Remediation debt — work required to fix once spotted

Closest to 'touches multiple files / significant refactor in one component' (e5). The quick_fix describes extracting nested ifs into guard clauses, extracting loops into named methods, and simplifying boolean conditions — this typically requires restructuring function internals and often creating new helper methods. Common mistakes note that naive splits just move complexity rather than reduce it, indicating non-trivial refactoring work.

b5 Burden Structural debt — long-term weight of choosing wrong

Closest to 'persistent productivity tax' (b5). This applies across all contexts (web, cli, queue-worker) and affects ongoing code review and maintenance decisions. High cognitive complexity creates a persistent drag on understanding and modifying code, but it doesn't define the system's architecture — it's a quality characteristic that can be addressed incrementally without rewrites.

t5 Trap Cognitive debt — how counter-intuitive correct behaviour is

Closest to 'notable trap' (t5). The misconception explicitly states that developers conflate cognitive complexity with cyclomatic complexity, assuming they're interchangeable when they measure different things. This is a documented gotcha that most developers eventually learn — nested conditions score higher than equivalent flat ones, which surprises those who only know cyclomatic complexity.

About DEBT scoring →

Also Known As

cognitive load mental complexity readability metric

TL;DR

A readability-focused complexity metric that penalises nesting more heavily than cyclomatic complexity.

Explanation

Introduced by SonarSource, cognitive complexity scores how hard code is to understand — not just how many paths it has. Structural elements add to the score based on nesting depth: a deeply nested if costs more than a top-level one. Breaks in linear flow (goto, break with label, recursion) also add penalties. Unlike cyclomatic complexity, it is designed to correlate with human comprehension difficulty rather than test case count.

Common Misconception

Cognitive complexity and cyclomatic complexity are interchangeable. Cyclomatic complexity counts paths; cognitive complexity weights how hard those paths are for a human to follow — nested conditions score higher than equivalent flat ones.

Why It Matters

Cognitive complexity measures how hard code is to understand — not just how many branches it has (cyclomatic complexity) but how deeply they nest. High cognitive complexity correlates with increased bug density and maintenance cost.

Common Mistakes

  • Reducing cyclomatic complexity (branch count) while ignoring nesting depth — both matter for readability.
  • Splitting a high-complexity function into many small private methods in the same class — you move complexity, not reduce it.
  • Targeting a specific score number without understanding which constructs drive it — nested loops and early breaks are the main culprits.
  • Ignoring complexity in test code — complex tests are hard to maintain and give false confidence.

Code Examples

💡 Note
SonarQube and PHPStan measure cognitive complexity. Unlike cyclomatic complexity, nesting is multiplied — deeply nested code scores higher.
✗ Vulnerable
// High cognitive complexity — 4 levels of nesting
function process($items, $user) {
    if ($user) {
        foreach ($items as $item) {
            if ($item->active) {
                if ($user->canView($item)) {
                    if ($item->type === 'special') { handleSpecial($item); }
                }
            }
        }
    }
}
✓ Fixed
// Lower complexity — early returns + extracted helpers
function process($items, $user): void {
    if (!$user) return;
    foreach ($items as $item) { $this->processItem($item, $user); }
}

private function processItem($item, $user): void {
    if (!$item->active || !$user->canView($item)) return;
    if ($item->type === 'special') handleSpecial($item);
}

Added 13 Mar 2026
Edited 4 May 2026
Views 143
Rate this term
No ratings yet
🤖 AI Guestbook educational data only
| |
Last 30 days
0 pings T 0 pings F 0 pings S 0 pings S 1 ping M 2 pings T 0 pings W 1 ping T 0 pings F 1 ping S 0 pings S 1 ping M 1 ping T 0 pings W 1 ping T 0 pings F 0 pings S 0 pings S 2 pings M 0 pings T 0 pings W 0 pings T 1 ping F 0 pings S 1 ping S 0 pings M 1 ping T 0 pings W 0 pings T 0 pings F
No pings yet today
No pings yesterday
Scrapy 16 Perplexity 15 ChatGPT 13 SEMrush 13 Google 8 Ahrefs 8 Amazonbot 7 PetalBot 5 Bing 4 Unknown AI 2 Twitter/X 2 Applebot 2 Brave Search 2 Meta AI 1 Qwen 1
crawler 93 crawler_json 6
DEV INTEL Tools & Severity
🟡 Medium ⚙ Fix effort: Medium
⚡ Quick Fix
Break functions scoring above 15 in cognitive complexity — extract nested ifs into guard clauses, extract loops into named methods, and simplify boolean conditions
📦 Applies To
any web cli queue-worker
🔗 Prerequisites
🔍 Detection Hints
Functions with deeply nested if/else/loops; multiple break/continue/return inside loops; complex boolean chains
Auto-detectable: ✓ Yes phpmd phpcs sonarqube phpstan
⚠ Related Problems
🤖 AI Agent
Confidence: High False Positives: Low ✗ Manual fix Fix: Medium Context: Function Tests: Update


✓ schema.org compliant