Why does the third increment trigger?
Cause of negation ! ? - other examples with single negation (before variable) doesn’t increment complexity counter.
Cause of second parentheses? - sonar-java skips parentheses in logical expressions during complexity compluting.
Maybe the ! AND parentheses make increment?
Pretty cool to learn that you are implementing the Cognitive Complexity metric! Out of curiosity, what language are you targeting?
As far as I remember from implementation (and looking at our implementations handling binary expressions in our PHP, JavaScript, Java plugins), the idea is to flatten the chain of binary expressions (ignoring parentheses), and increase complexity every time it changes operator:
A && B // +1
&& C // +0
&& D // +0
A && B // +1
|| C // +1
&& D // +1
In you case, however, I guess that the negation in the middle break the chain, introducing an extra +1. It also seems to me that logical complements are not taken into account in our computation. According to my tests on SonarJava, I can see that we are going to count your case like this:
if ( // +1
A
&& // +1
! // +0
( // +0
B
&& // +1
C
)
)
Good luck with your implementation!
I hope this helps!
Just to followup on Michael’s excellent answers, it’s the negation of a group that start a new series. Specifically !(b && c) in the example from the whitepaper is a new series because the reader must mentally translate / understand that: !(b && c) == !b || !c
so the whole sequence becomes: a && (!b || !c).
When written out like that the trickiness lurking in !(b && c) is a bit more obvious. And trickiness is what we’re counting here.
I’ll go back to the whitepaper and see if an expansion / clarification is in order.