Cognitive complexity tracks readability better than cyclomatic

Cognitive complexity tracks readability better than cyclomatic

Cyclomatic complexity counts the independent paths through a function — roughly one point per branch. It's a fine proxy for how many test cases you need. It's a poor proxy for how hard the function is to read, because it treats a flat list of guard clauses the same as the same number of branches buried five levels deep.

Cognitive complexity, from SonarSource, was built to fix exactly that. It weights nesting. A branch at the top level costs one. The same branch inside three enclosing blocks costs more, because each level you have to hold in your head to understand it. Boolean operator sequences add a point each. The result lines up with the intuition a reviewer already has: deeply nested code is the code that's hard to follow, even when its path count is modest.

Why keep both

They answer different questions, so track both and flag on whichever crosses its line:

In the Review System Changes Skill the thresholds are cyclomatic over 10 and cognitive over 15 (SonarSource's default). Breaching cognitive raises a hard-to-follow flag; breaching cyclomatic raises high-complexity. Two different smells, two different fixes.

The fix the number implies

The reason cognitive complexity is actionable is that its main driver — nesting — points straight at the remedy. Pull the innermost block into its own named function and every level above it drops by one. That's why the flag ships with a recommendation, not just a score. A bare "16" tells a reviewer nothing; "mostly nesting, extract the inner loop" tells them what to do. See A metric needs a recommendation to be actionable.

This is the measurable side of Clever Code Considered Harmful: clever code is usually dense code, and density shows up as cognitive load.