Having all branches of an if
chain, switch
statement or ternary operator with the same implementation indicates a
problem. The conditional structure is pointless, because the same code will be executed regardless of the conditions.
In the following code:
if (b == 0) { // Noncompliant
doOneMoreThing();
} else {
doOneMoreThing();
}
int b = a > 12 ? 4 : 4; // Noncompliant
switch (i) { // Noncompliant
case 1:
doSomething();
break;
case 2:
doSomething();
break;
case 3:
doSomething();
break;
default:
doSomething();
}
Either there is a copy-paste error that should be fixed; or the if
chain, switch
statement or ternary operator is
unecessary and should be removed.
This rule triggers when all branches, including the default branch, are identical. The default branch is the one that is executed when
none of the conditions of the structure are satisfied. This branch may present itself explicitly, implicitly, or by construction.
if (a == 0) b == 1;
else b == 2; // explicit default branch
int func() {
if (a == 0) return 1;
return 2; // implicit default branch
}
int b = a == 0 ? 1 : 2;
// ^ default branch by construction
switch (a) {
case 0:
return 1;
default: // explicit default branch
return 2;
}