CognitiveComplexity: count else/else-if as one complexity#5458
CognitiveComplexity: count else/else-if as one complexity#5458picklebento merged 3 commits intodetekt:mainfrom
Conversation
824997e to
c7d47fd
Compare
c7d47fd to
c1f4912
Compare
| } else if (condition) { // +2 | ||
| while(true) { // +3 | ||
| } | ||
| } else { // +2 | ||
| while(true) { // +3 | ||
| } | ||
| } |
There was a problem hiding this comment.
From #5447 and paper of Cognitive Complexity,
No nesting increment is assessed for these structures because the mental cost has already been paid when reading the if.
else and else if seem to be counted as +1 complexity only (do not include nesting level increments).
There was a problem hiding this comment.
I'm sorry @t-kameyama, I said something that could be misunderstood.
What I'm trying to say is
else if and else
- should add +1
complexity(Increments) - should increase
nesting level(Nesting Level) - should not add
complexity by nesting level(no Nesting increments)
Thus, the complexity of the test code should be 39
fun test(condition: Boolean) {
if (condition) { // +1
if (condition) { // +2
while(true) { // +3
}
} else if (condition) { // +1
while(true) { // +3
}
} else if (condition) { // +1
while(true) { // +3
}
} else { // +1
while(true) { // +3
}
}
} else if (condition) { // +1
if (condition) { // +2
while(true) { // +3
}
} else if (condition) // +1
while(true) { // +3
}
} else { // + 1
if (condition) { // +2
while(true) { // +3
}
} else // +1
while(true) { // +3
}
}
if (condition) { // +1
}
}
"""
// total 39 comple
The complexity suddenly increased, but I think this is a more real complexity (from the perspective of Cognitive Complexity)
BraisGabin
left a comment
There was a problem hiding this comment.
LGTM. @sanggggg it does follow what you were asking, right?
sanggggg
left a comment
There was a problem hiding this comment.
Yes, thank you for implementation! 🚀
| if (element.expression is KtIfExpression) { | ||
| super.visitKtElement(element) | ||
| } else { | ||
| complexity++ |
There was a problem hiding this comment.
💯 since an else branch only increment the complexity without adding nesting

Fixes #5447