What is Cognitive Complexity in sonar report?

Akshay Paliwal picture Akshay Paliwal · Oct 10, 2018 · Viewed 17.9k times · Source

Now a days i switched to sonar reports for static code review and performance improvement. Under the rules section I found that the cognitive complexity of my methods are high.

You can find cognitive complexity error in sonar as: Go to Project->Issues Tab->Rules Drop-down->Cognitive Complexity

Below screen shot gives you a reference of sonar project:

enter image description here

I was not getting any way to calculate and reduce the cognitive complexity of my methods. Finally I found the accurate way to calculate the complexity and i will answer this in my post below. Please check out.

Answer

Akshay Paliwal picture Akshay Paliwal · Oct 10, 2018

Cognitive Complexity

After searching some blogs and having chat with sonar team I found an easy definition and calculation of cognitive complexity which is as below:

Definition:

Cognitive Complexity, Because Testability != Understandability

Your written code must be as simple to understand as the above definition, simple.

less Cognitive Complexity more Readability

Let's see a method for example to calculate CC, right now I am referring kotlin language, see below image:

Sonar capture

In above image there is a method getAppConfigData(), whose cognitive complexity is being measured. Right now the CC of this method is 18. As you can check in above screen shot there is a warning, which tells that the limit of maximum complexity is 15, which is lower than the current CC of this method.

Now the actual question is: How can I calculate the CC of my method at the time of development?

Follow below rules to get your CC of any method or class as:

  • Increment when there is a break in the linear (top-to-bottom, left-to-right) flow of the code
  • Increment when structures that break the flow are nested
  • Ignore "shorthand" structures that readably condense multiple lines of code into one

So whenever above rules matches, just add + count to your CC and remember count will be increased according to level of code break, as example "if" condition gets +1 if it is the first code break but if you have used one more nested if then it will be a +2 for that inner "if" as shown in below image.

enter image description here

That's all I got in terms of Cognitive Complexity.

You can find everything related to CC at sonar blog

Thank You