Click here to Skip to main content
15,879,096 members
Articles / All Topics

Understanding Cyclomatic Complexity and Its Importance in Code Analysis Metrics

Rate me:
Please Sign up or sign in to vote.
2.54/5 (3 votes)
9 Sep 2015CPOL4 min read 14K  
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:

clip_image001

clip_image003

 

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

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 is clean and maintainable.

Let’s see some ways by which we can reduce the cyclomatic complexity:

  1. 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 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 blocks are doing some logic or returning something based on some condition, then it's 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 the 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:

    C#
    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.

  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 switchcase 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, 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 using switch 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 switchcase statements:

    clip_image013

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
Image 9 Image 10

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
United States United States
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
-- There are no messages in this forum --