Cyclomatic Complexity

ID

java.cyclomatic_complexity

Severity

low

Remediation Complexity

medium

Remediation Risk

low

Remediation Effort

medium

Resource

Complexity

Language

Java

Tags

complexity

Description

Reports methods, constructors, lambdas and anonymous-class bodies whose cyclomatic complexity (CCN) exceeds a configurable threshold.

CCN is the number of linearly independent paths through a function — effectively the count of decision points (if, else if, case, &&, ||, ?:, catch, loops) plus one. It is the canonical single number for how branchy a function is.

Rationale

High CCN correlates with hard-to-test, hard-to-maintain code: more paths mean more tests to cover them, more state combinations for a reader to keep in mind, and more places for a bug to hide. Deeply nested if chains, long else if ladders, and compound boolean conditions all raise CCN, so a single threshold captures patterns that would otherwise need several rules.

The rule is computed from the function’s data-flow graph as arcs - nodes + 2; test methods are excluded because arrange/act/assert chains legitimately branch through many cases.

Remediation

Extract helpers, replace chains with polymorphism or table lookups, and simplify compound boolean conditions until the function’s CCN is below the threshold. Prefer many small, testable functions over one large one.

// Before — CCN ~ 25
public int classify(int code) {
    if (code == 1) return ONE;
    else if (code == 2) return TWO;
    else if (code == 3) return THREE;
    // ... many more ...
    return UNKNOWN;
}

// After — CCN = 2
private static final Map<Integer, Integer> TABLE = Map.of(1, ONE, 2, TWO, 3, THREE /* ... */);
public int classify(int code) {
    return TABLE.getOrDefault(code, UNKNOWN);
}

Configuration

Property Default Description

maxCcn

20

Cyclomatic complexity strictly greater than this value is flagged.

References