Nested If
ID |
csharp.nested_if |
Severity |
low |
Remediation Complexity |
medium |
Remediation Risk |
low |
Remediation Effort |
medium |
Resource |
Code Smell |
Language |
CSharp |
Tags |
complexity, readability |
Description
Reports an if statement nested more deeply than a configurable threshold (default 4).
Deeply nested conditionals are hard to follow: the reader must keep every enclosing
condition in mind to understand the innermost branch. An else if continuation is not
counted as extra depth.
Rationale
Each extra level of nesting multiplies the number of states the reader must track and the
horizontal indentation pushes code off the screen. Most deep nests can be flattened with
guard clauses (early return/continue), by combining conditions, or by extracting the
inner block into a well-named method — all of which make the control flow linear and the
intent obvious.
// FLAW — depth 5 with the default limit of 4
if (a) { if (b) { if (c) { if (d) { if (e) { Run(); } } } } }
// OK — an else-if chain stays at depth 1
if (a) { A(); }
else if (b) { B(); }
else if (c) { C(); }
Remediation
Use guard clauses to return early, combine conditions with &&, or extract the deeply
nested block into its own method. The maximum allowed depth is configurable through the
maxDepth property.