Understanding Cyclomatic Complexity and Its Importance in Code Analysis Metrics






2.54/5 (3 votes)
Understanding cyclomatic complexity and its importance in Code Analysis Metrics
Cyclomatic Complexity
Cyclomatic complexity in code is software metric used to indicate the complexity in the program. It is a quantitative measure of the number of linearly independent paths through program's source code.
Read more about cyclomatic complexity here.
In normal terms, the cyclomatic complexity measure tells how complex your code is. Based on the numbers given per method in 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 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, 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
In Visual Studio, Go to 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 the complete solution compared 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 methods has more than 10 points, then it’s surely a candidate for refactoring. Remember, the lesser the number, the better it is maintainable.
Resolving Higher Cyclomatic Complexity
The main objective of understanding cyclomatic complexity to avoid excessive code complexity source code, so that it is clean and maintainable.
Let’s see some ways by which we can reduce the cyclomatic complexity:
- Validate and remove unwanted
if
statements: it's a known problem and a code issue that more the conditional statements, the more are the code complexities. First, validate and see whichif
statements can be removed so the code complexity is reduced. - 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.
- Remove unnecessary/redundant
else
conditions:if
theif
else
blocks are doing some logic or returning something based on some condition, then it's better to have just one singleif
statement, instead ofif..else
block. Remember that even theelse
in this case would be redundant. See the following example:Before:
- 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:
List<String> filteredList = originalList.where(s => matches(s));
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 the near future.
- Apply Strategy Pattern to get rid of long
switch
cases: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 yourswitch
..case
statement. Having said that, please ensure NOT to enforce strategy for smallerswitch
cases, if theswitch
cases are going to be extended over the period of time, then surely it’s a candidate for strategy, otherwise, it 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 usingswitch
statement in this case would be very long, so instead apply strategy pattern for achieving low cyclomatic complexity and clean code. - Apply Command pattern to reduce meat from
switch
…case
statements:
So we have seen how important cyclomatic is 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.
Filed under: CodeProject, Uncategorized