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.
Cognitive complexity is how complexly or simply people think about a particular issue.
Cognitive Complexity Rule. So we have the response from SonarQube: “Refactor this function to reduce its Cognitive Complexity from 26 to the 15 allowed.” Cognitive Complexity is a measure of how hard the control flow of a function is to understand. Functions with high Cognitive Complexity will be difficult to maintain.
To estimate the cognitive complexity we must first calculate the behaviour complexity ("BC") of each user and each task. Then we estimate the task complexity ("TC") of each task by searching for the minimum of the 12 empirical values of the behaviour complexity (the "best" solution).
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With