Understanding Cyclomatic Complexity and its Importance in Code Analysis Metrics
Cyclomatic complexity in code is software metric used to indicate the complexity of the program. It is a quantitative measure of the number is linearly independent paths through programs source code. Read more about cyclomatic complexity here.
In normal terms, the cyclomatic complexity measure tells how complex is your code. Based on the numbers given per method in the source code, one can easily tell if the code is complex or not. The cyclomatic complexity also affects other software metrics like code maintainability index. The cyclomatic complexity is more in the classes/methods where there are a lot of conditional operators (e.g if..else, while, switch statements). The number of lines in a class or a method also affects the cyclomatic complexity, more number of lines means, a combination of several logic altogether, which clearly violates SRP ( single responsibility principle).
Let’s see some examples of how cyclomatic complexity is being calculated:
Calculating Cyclomatic complexity using Visual Studio:
Resolving higher Cyclomatic complexity:
List<String> filteredList = originalList.where(s => matches(s));
5. Apply Strategy Pattern to get rid of long switch cases:
6. Apply Command pattern to reduce meat from switch…case statements:
In visual studio goto, Analyze option and select either the Calculate Code Metrics for Selected Projects or Calculate Code Metrics for Solution. As each option suggests, choosing the second option would analyze complete solution compare to the previous one which would analyze it for selected projects.
Clicking on either of the options would open up Code Metrics Results window that would show all the Analysis details. Result window contains analysis results in terms of Maintainability Index, Cyclomatic Complexity, Depth of Inheritance, Class coupling and Lines of code.
A good maintainable code would have code complexity less than 10 points. If any of your method is having more than 10 points, then it’s surely a candidate for refactoring. Remember, the lesser is the number the better it is maintainable.
The main objective of understanding cyclomatic complexity to avoid excessive code complexity source code, so that it clean and maintainable.
Let’s see some ways by which we can reduce the cyclomatic complexity:
1. Validate and remove unwanted if statements: its known problem and a code issue that more the conditional statements, the more are the code complexities. First validate and see which if statements can be removed so the code complexity is reduced.
2. Refactoring: refactoring is helpful in dealing with very high cyclomatic complexity of source code. The higher the number, the more it needs refactoring. Every developer should try refactoring bigger methods into smaller methods to reduce the code complexity. Use the single responsibility principle to break bigger classes into smaller ones thus reducing dependency on single class doing multiple functions.
3. Remove unnecessary/redundant else conditions: if the if. Else block are doing some logic or returning something based on some condition, then its better to have just one single if statement, instead of if..else block. Remember that even the else in this case would be redundant. See following example:
4. Combine conditions to reduce cyclomatic complexity: often the simple code would have some complexity, due to conditional statements, but rewriting those with simple LINQ conditions would reduce the count:
One word of caution is to be careful with such linq queries. If you think the query can get more complex, then it won’t serve the purpose, in that case it would be better to live with complexity of 2, rather than 1.
We want to keep the code readable as well as simple. So make sure your LINQ queries are not exploited in near future.
One good advice I would always give to developers is to use Strategy pattern, rather than switch…case statements. Remember that using a strategy pattern is a replacement to your switch..case statement. Having said that, please ensure NOT to enforce strategy for smaller switch cases, if the switch cases are going to be extended over the period of time, then surely it’s a candidate for strategy, otherwise, its won’t make much sense.
One good example of using strategy pattern over switch case would be a tax calculation problem for 50 states… you know that using swich statement in this case would be very long, so instead apply strategy pattern for achieving low cyclomatic complexity and clean code.
So we have seen how important is cyclomatic and why it was included in the visual studio code analysis toolset. Since it’s already available in visual studio, all the developers, leads and managers should take use of this to analyze code metrics and adhere to some numbers, which they feel would keep the code quality better.