Nested If

ID

kotlin.nested_if

Severity

low

Remediation Complexity

medium

Remediation Risk

low

Remediation Effort

medium

Resource

Code Smell

Language

Kotlin

Tags

complexity, readability

Description

Reports an if expression whose nesting depth within the enclosing function exceeds the configurable maxDepth threshold (default: 4).

Rationale

Deeply nested conditionals are hard to read, understand, and test. Each nesting level adds a new mental stack frame and multiplies the number of execution paths. Refactoring toward early returns, guard clauses, or extracted helper functions eliminates the nesting and makes the intent clear.

// Bad — 5 levels deep
fun check(a: Int, b: Int, c: Int, d: Int, e: Int): String {
    if (a > 0) {
        if (b > 0) {
            if (c > 0) {
                if (d > 0) {
                    if (e > 0) { // FLAW
                        return "all positive"
                    }
                }
            }
        }
    }
    return "other"
}

// Good — guard clauses flatten the nesting
fun check(a: Int, b: Int, c: Int, d: Int, e: Int): String {
    if (a <= 0 || b <= 0 || c <= 0 || d <= 0 || e <= 0) return "other"
    return "all positive"
}

Remediation

Use early returns or guard clauses to reduce nesting. If the logic is inherently complex, extract sub-conditions into named helper functions.