Cyclomatic Complexity

ID

kotlin.cyclomatic_complexity

Severity

info

Remediation Complexity

medium

Remediation Risk

low

Remediation Effort

medium

Resource

Complexity

Language

Kotlin

Tags

complexity

Description

Reports functions whose cyclomatic complexity (CCN) exceeds a configurable threshold (default: 30).

Rationale

fun veryComplex(a: Int, b: Int, c: Int): Int { // FLAW
    var r = 0
    if (a > 0) r++
    if (b > 0) r++
    if (c > 0) r++
    if (a > b) r++
    if (b > c) r++
    if (a == b && b == c) r++
    // ... and so on
    return r
}

Cyclomatic complexity counts linearly-independent paths through a function. The rule adds one for each branching construct: if (including else if), when entries (excluding else), loop conditions (for, while, do-while), short-circuit && and ||, the elvis operator ?:, and catch blocks. High CCN correlates with code that is hard to test, hard to read, and prone to regression.

Remediation

Extract sub-routines into helper functions, replace long if/else if chains with when, push validation into types (e.g. sealed hierarchies), or split the function along its natural seams.

Configuration

Property Description Default

maxCcn

CCN strictly greater than this value is flagged.

30