Rules / Complexity / avoid-nested-if
avoid-nested-if
Flags an if statement whose then-branch contains nested if statements.
Pyramid-shaped nesting is hard to follow; combining conditions with &&,
using early returns, or extracting a method flattens it. The rule counts the
if statements within a then-branch subtree and fires when at least two are
present (pyramid_lint's default max_nesting_level of two), so an if whose
body nests two further ifs is reported.
Invalid
example.dartdart
class NestedIfExamples {
// A vertical chain: the outer then-branch contains two further `if`
// statements (b and c), so the outermost `if` is flagged.
void chain(bool a, bool b, bool c) {
if (a) {
if (b) {
if (c) {
print('all true');
}
}
}
}
// Two sibling `if` statements inside the then-branch also reach the
// nesting threshold of two.
void siblings(bool a, bool b, bool c) {
if (a) {
if (b) {
print('b');
}
if (c) {
print('c');
}
}
}
// Nested `if` statements reached through an intervening loop still count.
void throughLoop(bool a, bool b, List<int> xs) {
if (a) {
for (final x in xs) {
if (b) {
if (x > 0) {
print(x);
}
}
}
}
}
void doSomething() {}
}
Avoid nesting if statements. Consider combining conditions or using early returns.
4 void chain(bool a, bool b, bool c) {
5 if (a) {
∙
Avoid nesting if statements. Consider combining conditions or using early returns.
16 void siblings(bool a, bool b, bool c) {
17 if (a) {
∙
Avoid nesting if statements. Consider combining conditions or using early returns.
28 void throughLoop(bool a, bool b, List<int> xs) {
29 if (a) {
∙
Valid
example.dartdart
class NestedIfExamples {
// A single level of nesting is allowed (default max_nesting_level is 2).
void singleNesting(bool a, bool b) {
if (a) {
if (b) {
print('both true');
}
}
}
// Combined conditions avoid nesting entirely.
void combined(bool a, bool b, bool c) {
if (a && b && c) {
print('all true');
}
}
// Guard clauses with early returns keep the body flat.
void guards(bool a, bool b) {
if (!a) {
return;
}
doSomething();
if (!b) {
return;
}
print('both conditions met');
}
// An if/else-if chain is a sibling chain, not nesting: each then-branch
// holds no further `if`.
void elseIfChain(int code) {
if (code == 1) {
print('one');
} else if (code == 2) {
print('two');
} else {
print('other');
}
}
void doSomething() {}
}
How to configure
Set the severity of avoid-nested-if in your falcon.json:
falcon.jsonjson
{
"linter": {
"rules": {
"complexity": {
"avoid-nested-if": "error"
}
}
}
}