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 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 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:

clip_image001

clip_image003clip_image005

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 the each option suggests, choosing second option would analyze complete solution compare to 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.

clip_image007

clip_image008

Resolving higher Cyclomatic complexity:

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:

clip_image009

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:

clip_image011

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 near future.

5. 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 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.

6. Apply Command pattern to reduce meat from switch…case statements:

clip_image013

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.

 

About Chetan VIHITE

an avid software developer with more than 12 years of experience in software development using .net, c#, ASP .net, MVC, Web API, NodeJs.
This entry was posted in CodeProject, Uncategorized. Bookmark the permalink.

Leave a comment