Both if-else chains and switch statements are used for conditional branching, but they differ in their syntax and the way
they handle multiple conditions.
- In an
if-else chain, each condition is checked in order, and only the block associated with the first true condition is executed.
If no condition is true, the code inside the else block (if present) will be executed.
- In a
switch statement, the expression is evaluated once, and its value is compared against each case. If a matching case is found,
the corresponding block of code is executed. The break statement is used to exit the switch block after a match. If no
case matches the expression, the code inside the default block (if present) will be executed.
Having the same condition in both if-else chains and switch cases can lead to unreachable code and a potential source of
bugs. It defeats the purpose of conditional branching and can make the code harder to read and maintain.
if (event === 1) {
openWindow();
} else if (event === 2) {
closeWindow();
} else if (event === 1) { // Noncompliant: Duplicated condition 'event === 1'
moveWindowToTheBackground();
}
switch (event) {
case 1:
openWindow();
break;
case 2:
closeWindow();
break;
case 1: // Noncompliant: Duplicated case '1'
moveWindowToTheBackground();
break;
}
Carefully review your conditions and ensure that they are not duplicated across the if-else chain or switch statement.
Use distinct conditions and default blocks to cover all scenarios without redundant checks.
if (event === 1) {
openWindow();
} else if (event === 2) {
closeWindow();
} else if (event === 3) {
moveWindowToTheBackground();
}
switch (event) {
case 1:
openWindow();
break;
case 2:
closeWindow();
break;
case 3:
moveWindowToTheBackground();
break;
}