Cognitive Complexity and its effect on the code

vmorusu picture vmorusu · Oct 10, 2017 · Viewed 19.4k times · Source

W.r.t to one of the java projects, we recently started using SonarLint. Output of the code analysis shows too many critical code smell alerts.

Critical code smell: Refactor this method to reduce its Cognitive Complexity.

I have heard about Cyclomatic Complexity but not about Cognitive Complexity. My questions to the group:

  • Is Cognitive Complexity an industry standard?
  • Impacts of Cognitive Complexity on code apart from readability and maintainability.
  • Does Cognitive Complexity apply only to methods or any other parts of code?
  • Any specific criteria on which Cognitive Complexity depends on?
  • Best practices to improve Cognitive Complexity of a code.

I have gone through this link but could not get answers to all my questions.

Thanks in advance.

Answer

Sorin picture Sorin · Oct 11, 2017

Humans can easily keep in mind about 7 entities +/- 2(wikipedia). When somebody needs to read the code they may run into this limit. Sometimes there are too many local variables to keep track of, or too many if/for statements. In all cases it makes it harder to understand what the code is supposed to do because it's hard to keep a mental picture of the algorithm.

Industry standard: No.

Readability and maintainability: It's easier to debug/improve code that is simple and easy to read.

Applies on methods or other parts: Everything that some human might want to understand. If you try to explain your design and I need to keep track of 20+ classes, I'll be lost. If I need to work quickly with your interface but I need to remember 10 bits of state, I won't be able to.

Any specific criteria it depends on: The amount of things one needs to remember to understand the code.

Best practices: Make more and better defined functions. Extract related concepts into groups/packages. Reduce the number of nesting levels in the code (if you read a nested code you need to remember the condition that got you there). Reduce the number of in use variables at any one point (works great with extracting functions).