Skip to content

ALL-FUNC0008 · cognitive_complexity

Measure how hard one callable is to follow, counting nesting against it.

This is a deterministic rule for all languages. Read its implementation.

Score the control structures a provider resolved inside one callable. Every structure that breaks the linear flow adds one. A structure that also nests adds nesting_penalty for each enclosing structure it sits inside. A jump, a recursion, and a sequence of mixed Boolean operators add one without a nesting penalty, because they interrupt reading without adding a level to hold in mind. An alternative arm such as else or elif adds one on its own since a reader must carry the earlier condition into it.

The measure is deliberately not cyclomatic complexity. A switch over twenty cases reads far more easily than three nested conditions, and only a nesting-aware score says so. The provider resolves what the structures are and how deep each one sits, and this rule owns the model, so the same score is comparable across every language a provider supports.

Each finding records the callable range and every scored structure with its kind, its nesting depth, and the increment it contributed. The value is the total score.

A callable whose structures a provider could not resolve scores zero rather than a guess. The score is a measurement and a project policy decides the acceptable ceiling, which differs between a parser, a request handler, and a test.

A callable holding one loop with one condition inside it returns 3, which is one for the loop, one for the condition, and one because the condition nests inside the loop. The same two structures written in sequence return 2. A callable with no control structure at all returns 0.

  • Cites “Cognitive Complexity”, a new way of measuring understandability. Open reference
  • Generalizes clang-tidy readability-function-cognitive-complexity. Open reference
  • Generalizes Clippy cognitive_complexity. Open reference