SonarQube Cognitive Complexity

Some functions read like a simple recipe. Others read like a maze with doors inside doors. Cognitive Complexity gives each function a score that predicts how hard a person finds it to understand. A lower score means easier reading, faster reviews, and fewer mistakes during changes.

The Road Map Picture

A straight road is easy to follow. A road with many turns needs more attention. A road with turns inside turns inside turns drives people crazy. Cognitive Complexity counts the turns and adds extra points for each level of nesting.

 Easy function                 Hard function
 ─────────────                 ─────────────
 start                         start
   │                             ├─ if A
   ├─ step 1                     │   ├─ if B
   ├─ step 2                     │   │   ├─ for each item
   └─ end                        │   │   │   └─ if C
 Score: 0                        │   │   └─ ...
                                 └─ ...
                               Score: 18

How the Score Grows

SonarQube follows three simple ideas.

  1. Code that reads straight from top to bottom costs nothing.
  2. Every break in that flow adds one point. Breaks include if, else, switch, loops, catch blocks, and chains of logical operators that mix and and or.
  3. Every break inside another break adds extra points equal to its nesting level.

A Worked Example

This function checks a shipping order.

function canShip(order) {
  if (order.paid) {                      // +1
    if (order.items.length > 0) {        // +2 (nested once)
      for (const item of order.items) {  // +3 (nested twice)
        if (!item.inStock) {             // +4 (nested three times)
          return false;
        }
      }
      return true;
    }
  }
  return false;
}
// Total score: 10

The logic is small, yet the score reaches 10 because every level hides inside the previous one.

The Flat Version

Guard clauses return early and keep the main path straight.

function canShip(order) {
  if (!order.paid) return false;                 // +1
  if (order.items.length === 0) return false;    // +1
  return order.items.every(item => item.inStock);  // +0
}
// Total score: 2

Both versions behave the same way. The second reads in seconds.

Cognitive vs Cyclomatic

FeatureCyclomaticCognitive
GoalCount test pathsEstimate reading effort
Nesting penaltyNoneYes
Switch with many casesHigh scoreLow score, since it reads simply
Best usePlan test casesJudge readability

The Rule Behind the Number

SonarQube raises a code smell when a function crosses a threshold. The default threshold for many languages is 15. The issue message shows the exact score and marks each line that adds points. Open the issue to see the little numbers placed beside the code.

Ways to Lower the Score

Use Early Returns

Handle bad cases first and leave the function immediately. The main path stays flat.

Extract Small Functions

Move a loop body into a function with a clear name. The parent function reads like an outline.

Replace Long Chains With Lookups

A table or map that connects values to actions often replaces a long run of else-if branches.

Name Conditions

Store a complex condition in a variable with a meaningful name, such as isEligibleForDiscount.

Where to See the Numbers

  1. Open a project and choose Measures.
  2. Select Complexity.
  3. Switch the view to Cognitive Complexity.
  4. Sort files from highest to lowest and start with the top few.

Cautions

  • Do not split code into dozens of tiny pieces just to lower a number. Unclear names make reading harder.
  • Some algorithms are complex by nature. Document them well and adjust the threshold for specific files if needed.
  • Write tests before refactoring so behavior stays safe.

A Review Meeting Scenario

A reviewer opens a pull request that changes a function with a score of 22. The discussion drags on, because nobody can follow every branch. The author extracts two helper functions and uses early returns. The score drops to 6, the review finishes in ten minutes, and a teammate spots a missing null check that the earlier version hid. Lower complexity makes human review faster and more accurate, which is the real value behind the number.

Setting a Team Threshold

Teams may change the threshold in the rule settings of a quality profile. Start with the default and tighten it gradually as habits improve. Discuss exceptions openly so nobody feels punished for hard problems.

Quick Recap

Cognitive Complexity rewards flat, readable code and penalizes deep nesting. Keep functions short, return early, and give every piece a clear name.