Nested If
ID |
go.nested_if |
Severity |
low |
Remediation Complexity |
medium |
Remediation Risk |
low |
Remediation Effort |
medium |
Resource |
Code Smell |
Language |
Go |
Tags |
complexity, readability |
Description
Reports an if statement whose nesting depth within the enclosing function exceeds the
configurable maxDepth threshold (default: 4). An else if chain is parsed as siblings of
the same if, not as a nested statement, so a long ladder does not raise the depth — only
genuinely nested if bodies do.
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
func check(a, b, c, d, 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 clause flattens the nesting
func check(a, b, c, d, 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.