Cognitive complexity measures how difficult code is to understand. Unlike cyclomatic complexity, which measures paths through the control-flow graph, cognitive complexity penalizes constructs that disrupt the linear flow of reading and rewards constructs that aid comprehension. The metric was introduced by SonarSource in 2018 explicitly to address shortcomings of cyclomatic complexity. It applies three rules:Documentation Index
Fetch the complete documentation index at: https://mehen.ophi.dev/llms.txt
Use this file to discover all available pages before exploring further.
- Ignore structures that allow multiple statements to be readably shorthanded into one.
- Increment for break in linear flow (
if,else, ternary,switch, loop,catch,goto, recursion,&&/||chains). - Increment for nested flow-breaking structures, with the increment proportional to the nesting depth.
What mehen emits
| Key | Type | Description |
|---|---|---|
cognitive | int | Cognitive complexity for the space. |
cognitive.sum | int | Sum across child spaces. |
cognitive.average | float | Mean across functions. |
cognitive.min | int | Minimum across functions. |
cognitive.max | int | Maximum across functions. |
How it differs from cyclomatic
Per-language increments
mehen mirrors Sonar’s specification closely. Each language analyzer contributes:- +1 for each control-flow break:
if,else if,else, ternary,switch(Sonar counts theswitchitself, not eachcase), loop,catch,goto, recursive call, etc. - +1 per nesting level of the construct relative to its enclosing function.
- +1 for each change in a sequence of
&&/||operators (chains of the same operator do not re-charge).
How to read it
| Value | Interpretation |
|---|---|
| 0–5 | Easy to read. |
| 6–10 | Moderate; usually fine. |
| 11–15 | Hard; consider extracting helpers. |
| 16+ | Likely a refactor candidate — readers will get lost. |
References
- Campbell, G. A. (2018). Cognitive Complexity — A new way of measuring understandability. SonarSource white paper. PDF.
- Muñoz Barón, M., Wyrich, M. & Wagner, S. (2020). An empirical validation of cognitive complexity as a measure of source code understandability. ESEM 2020. arXiv:2007.12520.
- Sonar: Cognitive complexity in metric definitions.
See also
- Cyclomatic complexity — paths through the CFG.
- Halstead metrics — vocabulary-based complexity.
- Maintainability Index — composite that blends cyclomatic + Halstead + LOC.