Issues with Cyclomatic Complexity metric in SonarQube

SonarQube version – Version 7.1 (build 11001)

In my SonarQube quality gate, I have added the Cyclomatic Complexity metric - Throw a ‘warning’ if it is greater than 20 and ‘error’ if it is greater than 1000.

The problem is all my projects currently throwing a ‘Warning’ message because of Cyclomatic Complexity.

My understanding is that SonarQube looks at various keywords like – if, while, for, switch, case, throw, return etc and increments the counter for each of the occurrence – and comes up with a final value for Cyclomatic Complexity. This metric is nice to have since it identifies the classes/methods which have too much of business logic going on – and probably are good candidate to be broken down and even rigorously unit tested.

However I think this metric should be working on a Method or Class level and not on a Project level.

I would like to focus more on classes/methods which have relatively high Cyclomatic Complexity value – and look at opportunities to decouple logic and break down the classes/methods further. Generally a class/method with high CC value indicates violation to the ‘Single Responsibility Principle’.

What is the guidance around recommended value of Cyclomatic Complexity for an application?

Is there a way in which this metric can be looked up at a Method level? For ex – If I set the CC value as 20, it displays methods/classes which have CC greater than 20.

My project is throwing a warning since CC>20. When I look at the details, I have few classes with CC value of 5,4,3. There is hardly any scope of optimization here. I don’t want to consider refactoring classes/methods if they have a Cyclomatic Complexity less than 20 say.

Hi there,

Then it seems like what you’re looking for is Rules checking complexity: https://next.sonarqube.com/sonarqube/coding_rules?q=complex&tags=brain-overload . If you enable some of those in your quality profile, then issues will be raised whenever a specific class/method breaches the defined complexity threshold ! (while we’re on the complexity topic, here’s a good read about cognitive complexity too).

1 Like