I’ve noticed an inconsistency in how SonarQube Cloud calculates cognitive complexity for logical operators (&& and ||). In some cases, Sonar counts these operators multiple times within the same condition, while in other cases, it seems to count them only once.
Additionally, I’ve observed that sometimes the cognitive complexity from one method appears to affect another method, increasing the reported complexity unexpectedly. This behavior seems random and inconsistent.
The screenshot attached are of our private project
Cognitive Complexity increments for sequences of logical operators. From the white paper:
Cognitive Complexity does not increment for each binary logical operator. Instead, it assesses a fundamental increment for each sequence of binary logical operators. For instance, consider the following pairs:
a && b
a && b && c && d
a || b
a || b || c || d
Understanding the second line in each pair isn’t that much harder than understanding the first. On the other hand, there is a marked difference in the effort to understand the following two lines:
a && b && c && d
a || b && c || d
What language are we talking about here? And can you provide a fuller screenshot of this, please?
Hi,
Thanks for warm welcome.
The language in the screenshot is Typescript. I can’t share more screenshots as these are of private git repositories. Although, I’ve added two screenshots:
1. First Screenshot
The && operator is adding 6 cognitive complexity. I don’t get why it is being calculated as 6 even on first line of the method without nesting. This has happened in 6 files in our 2 repositories analysis.
2. Second Screenshot
getStartAndEndDate() {
// ... this has 9 cognitive complexity
}
getMonthRange() {
// ... this have 2 cognitive complexity
}
The cogntive complexity of getMonthRange method is also being added into getStartAndEndDate method’s complexity, resulting 11 together. Ideally both should have seperate cognitive complexity. Right ?
Me either. That’s why I wanted to see more of the context. What I suspect is that complexity increments for further down the file are being wrongly attached to that location.
Can you provide a reproducer for each screenshot? What I’m asking for is anonymized code snippets that recreate the problems.