SonarCube Cognative Complexity reports all complexity for all functions as one metric

For Python code, SonarCube reports “Refactor this function to reduce its Cognative Complexity from 28 to the 15 allowed.” The problem is that in this function there are only 14 identified complexities. The remaining complexities are coming from other functions in the file.

It appears that SonarCube doesn’t make a distinction between functions (maybe only @staticmethod functions) and is therefore reporting the complexity as if all the functions were merged into a single function.

If a file has 20 functions, each with a single complexity, this would be over the Cognative Complexity limit of 15 when obviously a single line function isn’t that complex.

Hey there.

There are 14 issue locations, but if you look on the left, you’ll see statements like +2 (incl 1 for nesting). Add up all the +1, +2, and +3 for that issue and you get 28! :slight_smile:

What does (incl X for nesting) mean?

If an if statement has a nested if statement, that second if statement will make the Cognitive Complexity for a function increment by 2. If that second if statement has another nested if statement, it will increment by 3.

Everything looks like it’s functioning correctly.

The Whitepaper on Cognitive Complexity is an interesting read if you’re looking for a deeper dive.

Colin

1 Like

My apologies. Apparently I misunderstood how the metrics were being reported. From your comment I now see that the red boxes are just an indicator of what line to look at and the sum of all the numbers in grey is the cognitive complexity.

Thank you for setting me straight, and in such a timely manner.