Why this matters
Using if statements as the only statement in an else block adds unnecessary nesting and reduces code readability. Replace them with else-if to make the logic clearer and easier to follow.
Detect unnecessary nesting where an if statement is the only statement inside an else block. Recommend using else-if instead for improved readability.
Using if statements as the only statement in an else block adds unnecessary nesting and reduces code readability. Replace them with else-if to make the logic clearer and easier to follow.
Side-by-side examples engineers can pattern-match during review.
if (condition1) {
// ...
} else {
if (condition2) { // Noncompliant: 'if' statement is the only statement in the 'else' block
// ...
}
}
if (condition3) {
// ...
} else {
if (condition4) { // Noncompliant: 'if' statement is the only statement in the 'else' block
// ...
} else {
// ...
}
}if (condition1) {
// ...
} else if (condition2) {
// ...
}
if (condition3) {
// ...
} else if (condition4) {
// ...
} else {
// ...
}if (condition1) {
// ...
} else {
if (condition2) { // Noncompliant: 'if' statement is the only statement in the 'else' block
// ...
}
}
if (condition3) {
// ...
} else {
if (condition4) { // Noncompliant: 'if' statement is the only statement in the 'else' block
// ...
} else {
// ...
}
}if (condition1) {
// ...
} else if (condition2) {
// ...
}
if (condition3) {
// ...
} else if (condition4) {
// ...
} else {
// ...
}From the same buckets as this rule.
Check if loops use equality operators (== or !=) in termination conditions. These can lead to infinite loops if the condition is never met exactly. Instead, use relational operators like < or > for safer loop termination.