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:
Before:
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:
Before:
After:
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.
Write a comment
- multikonsults.com May 26, 2016, 2:00 amThanks for another magnificent article. Where else may just anybody get that kind of info in such a perfect approach of writing? I have a presentation subsequent week, and I am at the search for such information.reply
- Best Deer Attractant For Trail Cam May 17, 2016, 12:45 amHi there! This post couldn't be written any better! Reading this post reminds me of my good old room mate! He always kept talking about this. I will forward this article to him. Pretty sure he will have a good read. Thank you for sharing!reply
- Lydia May 13, 2016, 12:42 pmActually no matter if someone doesn't be aware of then its up to other users that they will assist, so here it occurs.reply
- Ingin aman bermain poker online, pilihlah agen yang tepat May 13, 2016, 7:21 amKeep on writing, great job!reply
- Poker Boyaa May 11, 2016, 10:26 pmAppreciate this post. Will try it out.reply