Introducing Cyclomatic Complexity in C#

As a programmer is developing software, there will be times when you need to know how complex a method is. Maybe the code is not doing what it should be doing and you need to refactor it to understand why. Maybe it is taking too long to run and you want to see if simplifying the code would make any difference. Or maybe a C# developer inherited a project where a method has gotten so out of control that nobody has any idea what is going on anymore. These are situations when knowing the cyclomatic complexity of your code can help identify areas for improvement.

Cyclomatic complexity can be used to quantify the linearly independent paths within source code. It helps you to understand the complexity of your program and improve code coverage. It is determined by the number of conditional branches and constructs in your code. So, cyclomatic complexity will be high for methods with a large number of conditional constructs and low for methods with few constructs.

Read: Dependency Injection in C#

What is Cyclomatic Complexity?

Cyclomatic complexity is a metric used to measure the complexity of your code. This is determined by the complexity and number of conditional branches in your code. To do this, you should calculate the number of linearly independent paths through a method. Cyclomatic complexity is independent of the language in which the code was written, but for this programming tutorial, we will be looking at it through the lens of the C# programming language.

Cyclomatic complexity is a quantitative measure of the number of linearly independent paths through a program’s source code. For example, if you have an if statement in your code, this would add one path through your execution. If you had an if-else statement, for every additional condition that was met it would add another path. Each switch statement is also calculated as one, plus the number of case statements contained in it.

Cyclomatic complexity is expressed as a number from 1 to 100. The lower the number, the simpler your code is. While a high value of cyclomatic complexity indicates the method is complex, a low value indicates that the method is simple to understand, test, and maintain.

How to Calculate Cyclomatic Complexity

The way it works is as follows: you create a graph from your code. Each node corresponds to a statement in your code. Edges are what connect the nodes together. In other words, an edge is a connecting line between the nodes, and a node represents a logical branch.

Cyclomatic complexity can be calculated as follows:

M = E − N + 2 * P

Where:

    • M = cyclomatic complexity
    • E = number of edges of the graph
    • N = number of nodes of the graph
    • P = number of connected components

Cyclomatic Complexity Tutorial in C#

Figure 1: Illustrating Cyclomatic Complexity

The higher the cyclomatic complexity, the more test cases you will need for your method. A lower value for cyclomatic complexity (a value below or equal to 10 being considered extraordinary) means that the code is presumed to be well-structured and highly maintainable.

Read: C# Tools for Code Quality

Programming Cyclomatic Complexity in C#

To calculate cyclomatic complexity, you should consider a graph that comprises nodes and edges. Refer to the following code snippet for an example of how to program cyclomatic complexity in C#:

    public static int DisplayText(string message)
    {
        var text = message;
        Console.WriteLine(text);
        return text.Length;
    }

The cyclomatic complexity for the above method is 1. There are two nodes and one edge. hence M = 1 – 2 + 2 x 1 = -1 + 2 = 1.

The following method will have a cyclomatic complexity of 2:

    public static int DisplayText(string message, bool display)
    {
        var text = message;
        if (display)
            Console.WriteLine(text);
        return text.Length;
    }

Refer to Figure 1 above, which illustrates how the above DisplayText method can be represented using nodes and edges. There are four nodes and four edges. Hence, M = 4 – 4 + 2 x 1 = 0 + 2 = 2.

Here is the complete source code for your reference:

public class CyclomaticComplexityExample
{
    public static int DisplayText(string message)
    {
        var text = message;
        Console.WriteLine(text);
        return text.Length;
    }
    public static int DisplayText(string message, bool display)
    {
        var text = message;
        if (display)
            Console.WriteLine(text);
        return text.Length;
    }
}

How to Reduce Cyclomatic Complexity

To reduce cyclomatic complexity, you can replace the conditional constructs in your code with polymorphism. You may add a lot of flexibility to your code by leveraging polymorphism; your code becomes more testable, and you can add, update, or even delete statements without much change in your code. The lower the degree of cyclomatic complexity, the easier it is to comprehend, test, and maintain your code.

In certain circumstances, you can use behavioral design patterns such as the Strategy design pattern to reduce cyclomatic complexity in your code.

Read: Productivity Tools for .NET Developers

Why is Cyclomatic Complexity Important?

The complexity of a codebase has a significant impact on the time it takes to develop, test, and maintain. Apart from that, high complexity software is usually more prone to bugs. If you want your code to be bug-free, you want it to be as simple as possible. Cyclomatic complexity is a good indicator of how hard your code will be to maintain. Code with low complexity is generally easier to understand because it is shorter and has fewer branches. This may make it easier to add new functionality and easier to maintain.

The reason cyclomatic complexity is important is that it can be used to determine how difficult the maintenance and testing of your application will be and how likely you are to introduce errors into your codebase during development or subsequent updates. This means that it directly affects the quality of your software, which can lead to better customer satisfaction and product consistency.

Final Thoughts on Cyclomatic Complexity

Visual Studio now supports the calculation of cyclomatic complexity with the Visual Studio IDE, which means code metrics can be calculated either for the whole solution or for the selected projects. The Code Metrics Results window displays the code analysis results from the code analysis in three ways: Maintainability Index, Cyclomatic Complexity, and Depth of Inheritance.

Read more C# programming tutorials and software development guides.

Joydip Kanjilal
Joydip Kanjilal
A Microsoft Most Valuable Professional in ASP.NET, Speaker, and Author of several books and articles. More than 25 years of experience in IT with more than 18 years in Microsoft .NET and its related technologies. He was selected as a Community Credit Winner at http://www.community-credit.com several times. He has authored 8 books and more than 500 articles in some of the most reputed sites worldwide including MSDN, Info World, CodeMag, Tech Beacon, Tech Target, Developer, CodeGuru, and more.

More by Author

Must Read