Chances are, you are very familiar with the feeling of trying to understand someone else's (or even your own) old code. It definitely made sense six months ago, but between then and now it has become more 'magic eye' than map. If you focus on how hard your code is to understand today, tomorrow will be a lot easier. Cognitive Complexity is Sonar's measure to help you do exactly that! This blog dives into how Cognitive Complexity is calculated and how it can help you write great code!
When collaborating with a team, it’s very important to consider how well the code you write will be read later in development. Cyclomatic Complexity was first introduced as a way to gauge how easy it is to test and maintain a module's control flow. While it's pretty good at assessing testability, the mathematical model behind it falls short when it comes to measuring maintainability. In this video, we observe a few examples:
Linear code is your friend. If all code was just a sequence of commands listed one after another without any looping or mucking about, then it would be pretty easy to hold that in your head. As soon as you add loops, or decisions that branch the code, it becomes more and more difficult to understand. For this reason, the Cognitive Complexity score for your code will increase by 1 each time you do that. In this video, we see how one’s score adds up when branching and looping are introduced. Sonar can help you see where the complexity is in your code, and seek our opportunities for refactoring.
Nested code is harder to understand and doing more inside nested code compounds how much effort it takes to hold everything in your head. In this video, we see how doing looping or branching inside other loops and branches can drastically impact your Cognitive Complexity score.
There are a number of constructs that are designed to make code clearer. Cognitive Complexity scoring is smart enough to understand these constructs do good, so using them won't increase your Complexity score. In this video, we observe a handful of examples that can help educate users on how Sonar’s Cognitive Complexity algorithm works.
In this video, we see how Sonar helps users understand complicated code through Cognitive Complexity scoring. Whether you look at the issue in your IDE with SonarLint or in SonarCloud or SonarQube, you can see each of the points in the function that impacts your overall score.
Cognitive Complexity provides a fresh take on complexity modeling. It yields method complexity scores that align well with how developers perceive maintainability. This has been a brief overview of how Sonar measuring Cognitive Complexity can help you write code that is easy to understand. Your team and future you will thank you for it!
Check out this White Paper on Cognitive Complexity by Community Manager, Ann Campbell!