Cyclomatic Complexity

ID

csharp.cyclomatic_complexity

Severity

low

Remediation Complexity

medium

Remediation Risk

low

Remediation Effort

medium

Resource

Complexity

Language

CSharp

Tags

complexity

Description

Reports a method, constructor, accessor or lambda whose cyclomatic complexity (CCN) exceeds a configurable threshold. CCN counts the number of linearly independent paths through the body — every if, for, while, case, catch, &&/|| and ?: adds a branch — so a single number captures how much branching the function packs in.

Rationale

A high CCN means many independent paths, which in turn means many test cases are required to exercise the code and many states a maintainer must hold in their head. Such functions are where defects cluster and where future changes are most likely to introduce regressions. Splitting the work into smaller, named helpers lowers the per-function complexity and makes each piece testable in isolation.

// FLAW — many branches push CCN above the limit
int Classify(int a, int b, int c)
{
    if (a > 0) { if (b > 0) { if (c > 0) return 1; else return 2; } else return 3; }
    else if (a < 0) { if (b < 0) return 4; else return 5; }
    else if (b > 0 && c > 0) return 6;
    else if (b < 0 || c < 0) return 7;
    return 0;
}

// OK — single clear path
int Double(int x) => x * 2;

Remediation

Extract cohesive blocks of branching into well-named helper methods, replace long if/else if chains with a switch expression or a lookup table, and use guard clauses to flatten nesting. Each extracted piece carries its own (lower) complexity.