Nested If
ID |
swift.nested_if |
Severity |
low |
Remediation Complexity |
medium |
Remediation Risk |
low |
Remediation Effort |
medium |
Resource |
Complexity |
Language |
Swift |
Tags |
complexity |
Description
Reports an if statement whose nesting depth exceeds a configurable
threshold. The depth counts enclosing if, guard, switch, for-in,
while and repeat-while statements within the same function body.
Rationale
Each level of nesting hides the precondition under which the inner code runs. Past four levels, readers must hold too many active conditions in their head and shape coverage by hand. The test count grows multiplicatively with the depth and the meaning of each branch becomes harder to reason about.
Notes
-
else ifchains are siblings of the outerif, not children of it — the rule does not penalise them. -
Only the inner-most offending
ifis flagged so the issue count tracks the number of refactorable spots, not the size of the chain.
Remediation
Common refactors are:
-
invert the leading condition and
guardearly; -
extract the deepest branch into a helper function;
-
replace a deeply-nested chain of
ifwith aswitchover a single value.
// Hard to read — many active conditions.
if let user = user {
if user.isActive {
if let email = user.email {
if isValid(email) {
send(email)
}
}
}
}
// Same logic, flat.
guard let user = user, user.isActive else { return }
guard let email = user.email, isValid(email) else { return }
send(email)