Fri, Nov 4 2005 11:59 AM Erwyn van der Meer

CA1502: Avoid Excessive complexity - Code analysis rule in VS2005

Jan Schreuder has blogged on BloggingAbout.NET before about cyclomatic complexity. Go read it if you don't know the importance of keeping the cyclomatic complexity of methods reasonably low. Jan mentioned the tool DevMetrics to check it. I used C# Refactory in the past for calculating metrics.

Code analysis in Visual Studio 2005 Team System now includes a rule to enfore this as well. The rule is CA1502: Avoid Excessive complexity and can be found in the Maintainability Rules category. The VS2005 documentation states this about the rule:

Cyclomatic complexity measures the number of linearly independent paths through the method, which is determined by the number and complexity of conditional branches. A low cyclomatic complexity generally indicates a method that is easy to understand, test, and maintain. The cyclomatic complexity is calculated from a control flow graph of the method and is given as

cyclomatic complexity = the number of edges - the number of nodes + 1

where a node represents a logic branch point and an edge represents a line between nodes.

The rule reports a violation when the cyclomatic complexity is greater than 25. The following cyclomatic complexity thresholds determine the Message Level associated with the violation:

25 < Warning
50 < Critical Warning
75 < Error
100 < Critical Error

I think 25 is too high a value before giving a warning. Unfortunately these limits are set in stone in VS2005 and cannot be changed. The values given here seem more reasonable to me:

Cyclomatic Complexity Risk Evaluation
1-10 a simple program, without much risk
11-20 more complex, moderate risk
21-50 complex, high risk program
greater than 50 untestable program (very high risk)
Filed under:

# re: CA1502: Avoid Excessive complexity - Code analysis rule in VS2005

Friday, November 04, 2005 6:04 AM by Jan Schreuder

I couldn't agree more. Keeping code as simple as possible makes it easier to understand, easier to test and easier to maintain. I also stick to the values you found at the SEI site.

There are some exceptions to the rule though. I found a method yesterday which has a complexity of 49. When I checkit, there was only 1 switch statement in the code with aproximately 130 case statements. The method returned error messages for error values. Not too complex I think, but there's certainly a huge number of branches.

# re: CA1502: Avoid Excessive complexity - Code analysis rule in VS2005

Friday, November 04, 2005 6:12 AM by Erwyn van der Meer

Jan, the method you mentioned is indeed a candidate for exclusion from this rule. The Visual Studio docs state:

"It is safe to exclude a warning from this rule if the complexity cannot easily be reduced and the method is easy to understand, test, and maintain. In particular, a method that contains a large switch (Select in Visual Basic) statement is a candidate for exclusion."