Cognitive and Cyclomatic complexity

Cognitive Complexity

After searching some blogs and having chat with sonar team I found an easy definition and calculation of cognitive complexity which is as below:

Definition:

Cognitive Complexity, Because Testability != Understandability

Your written code must be as simple to understand as the above definition, simple.

less Cognitive Complexity more Readability

Cognitive and Cyclomatic complexity

  1. Avoid if-else statements using collections

How to find out cognitive complexity for functions in golang?

If sonarqube flags certain files or functions as having a cognitive complexity of more than 15 (or whatever threshold it has), how do we deal with it in local machines?

Making code changes and uploading them to source control and running the CICD pipeline to look at the sonar report is a tedious process.

Instead, use https://github.com/uudashr/gocognit

By using gocognit, we can gain valuable insights into the understandability of your Go functions and identify areas that might benefit from refactoring to improve code maintainability.

Navigate to the directory containing the file and run gocognit <filename>

Other options

https://github.com/go-critic/go-critic

Tags

SonarQube


Links to this note