Cognitive Complexity
A measure of how difficult code is to understand, complementing cyclomatic complexity with human readability factors.
Also known as: Code Cognitive Complexity
Category: Techniques
Tags: software-development, code-quality, metrics, readability, maintainability
Explanation
Cognitive Complexity is a software metric developed by SonarSource that measures how difficult a piece of code is for a human to understand. Unlike cyclomatic complexity (which counts decision points), cognitive complexity considers the mental effort required to read and comprehend code.
Key Principles:
1. Nesting Increases Complexity: Nested structures (if inside if, loops inside loops) exponentially increase mental burden. Each level of nesting adds to the complexity score.
2. Breaks in Linear Flow: Control flow interruptions like break, continue, goto, and multiple return statements add complexity.
3. Shorthand Doesn't Reduce Complexity: Using ternary operators or null coalescing doesn't reduce cognitive load even if it reduces line count.
Scoring Rules:
- Basic increment (+1) for: if, else if, else, switch, for, while, do while, catch, conditional operators
- Nesting increment (+1) for each level of nesting
- No increment for: method calls, sequences of statements, boolean operators within same condition
Benefits Over Cyclomatic Complexity:
- Better reflects actual human comprehension difficulty
- Accounts for nesting depth
- Recognizes that some structures are harder to understand than others
- Produces more actionable feedback for developers
Applications:
- Code review guidelines
- Technical debt assessment
- Refactoring prioritization
- Code quality gates in CI/CD
Maintaining low cognitive complexity leads to more maintainable, readable, and bug-resistant code.
Related Concepts
← Back to all concepts