sonarqubesonarqube-web

SonarQube: Qualify Cognitive Complexity


I understand what cognitive complexity is and how it will be calculated, but i don't now how to determine what is a good value for that measure, so how complex my code schouldn't be. I need an objective way to estimate it without to compare project against each other. A kind of formula like "complexity/lines code" or something like that. Or if i define a quality gate for a big project how can i calculate the values for it.


Solution

  • At a method level, 15 is a recommended maximum.

    At the class level, it depends on what you expect in the package.

    For instance, in a package that should only hold classes with fields and simple getters or setters, a class with a Cognitive Complexity over 0 (5? 10?) probably deserves another look.

    On the other hand, in a package that holds business logic classes, a class score >= ... 150(?) might indicate that it's time to look at splitting the class.

    In terms of what the limit should be for a project, that's unanswerable, and brings us back to Fred Brooks' essential vs accidental complexity. Basically, there's a certain amount of logic that's required to get the job done. Complexity beyond that is accidental and could theoretically be eliminated. Figuring out the difference between the two is the crux of the issue, and in looking for the accidental complexity I would concentrate on methods where the complexity crosses the default threshold of 15.

    To answer your initial question, "What should the limit for an application be?", I would say there shouldn't be one. Because the essential complexity for a simple calculator app is far, far lower than for a program on the Space Shuttle. And if you try to make the Space Shuttle program fit inside the calculator threshold, you're absolutely going to break something.

    (Disclosure: I'm the primary author of Cognitive Complexity)