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