Share via


Avoid excessive complexity

TypeName

AvoidExcessiveComplexity

CheckId

CA1502

Category

Microsoft.Maintainability

Breaking Change

NonBreaking

Cause

A method has an excessive cyclomatic complexity.

Rule Description

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.

How to Fix Violations

To fix a violation of this rule, refactor the method to reduce its cyclomatic complexity.

When to Exclude Warnings

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. The risk of destabilizing the code base late in the development cycle or introducing an unexpected change in runtime behavior in previously shipped code might outweigh the maintainability benefits of refactoring the code.

Avoid excessive inheritance