Hello everyone,
The current Sonarlint setting for maximum cognitive complexity in a code block is 5. I’ve encountered situations where this feels overly restrictive, potentially leading to refactoring for compliance rather than clarity. I’d like to discuss if increasing this value would be beneficial. I believe a limit of 7 might be more appropriate.
I also have a lot of trouble and frustration with this, as it forces me to break down code into unreasonably small chunks, which I think don’t benefit anyone.
Thanks for bringing it up!
I’ve found it frustrating sometimes being forced to not go past the limit of 5, but I’d say after I refactor despite the frustration, I end up with self-documenting methods that have the “least surprise”.
Having said that, I see an argument for making it 7 to reduce the frustration.
But seriously, I agree with @Ben_Kiarie on this. In my experience, a cognitive complexity of 5
allows for each function to contain a meaningful amount of logic, but requires me to make the extra effort of breaking down particularly complex sequences into multiple self-documenting functions that can be reasoned about independently.
I will 100% grant that folks here are very capable of writing excellent performant bug-free code with a complexity much higher than 5
. However, for that code to be “maintainable” folks like me still need to be able to read it and understand what is going on…
That being said, 5
was just a magic number Craig picked because we needed an initial value to set for the rule, so there is nothing stopping us from changing that to a more useful value. Perhaps an interesting follow-up question is why 7
(and not 10
or some higher value)? Do you feel that 5
is too low to be able to include meaningful logic in a function?
(I would also be happy with lowering the limit if we decided that is useful! The older I get the more I like my functions to follow the Unix philosophy of “do one thing well”…)
7 is just a random number as well. It is just a slight increase from the number that we have right now, but not too much to cause the complexity of the functions to get too high.