Conditional expressions which are always true
or false
can lead to unreachable code.
Noncompliant code example
a = false;
if (a) { // Noncompliant
doSomething(); // never executed
}
if (!a || b) { // Noncompliant; "!a" is always "true", "b" is never evaluated
doSomething();
} else {
doSomethingElse(); // never executed
}
Exceptions
This rule will not raise an issue in either of these cases:
- When the condition is a single
final boolean
final boolean debug = false;
//...
if (debug) {
// Print something
}
- When the condition is literally
true
or false
.
if (true) {
// do something
}
In these cases it is obvious the code is as intended.