vmorusu
vmorusu

Reputation: 936

Cognitive Complexity and its effect on the code

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:

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

Thanks in advance.

Upvotes: 31

Views: 26653

Answers (1)

Sorin
Sorin

Reputation: 11968

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).

Upvotes: 38

Related Questions