Skip to main content
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:
  1. Ignore structures that allow multiple statements to be readably shorthanded into one.
  2. Increment for break in linear flow (if, else, ternary, switch, loop, catch, goto, recursion, &&/|| chains).
  3. Increment for nested flow-breaking structures, with the increment proportional to the nesting depth.

What mehen emits

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 the switch itself, not each case), 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

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