18

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.

Pixel-Killer
  • 241
  • 1
  • 3
  • 10

1 Answers1

39

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)

G. Ann - SonarSource Team
  • 22,346
  • 4
  • 40
  • 76
  • 1
    Thank you for helping, it's very awesome to get information from the original inventer. I appreciate that very much. I think now i am able to work with it. – Pixel-Killer Jul 14 '17 at 09:53
  • this was rather the best explanation so for in few lines , i had a question regarding the method level Cognitive Complexity - if my method needs to have more conditional statements - ( if/else - switch ) - and after a specific limit - in my case am not able to bring it down below 25-30 - what possible can be the work around to reduce the method level Cognitive Complexity – Ashish Shetkar Aug 23 '18 at 09:26
  • 2
    @AshishShetkar some refactoring methods are discussed [in this video](https://www.youtube.com/watch?v=x5V2nvxco90&t=17m) – G. Ann - SonarSource Team Aug 23 '18 at 14:10
  • 1
    Fyi on Shuttle Complexity : http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.711.2976&rep=rep1&type=pdf –  Feb 23 '21 at 11:43