if / else-if chain has no final else clause
ID |
scala.correctness.if_else_chain_without_else |
Severity |
low |
Remediation Complexity |
medium |
Remediation Risk |
low |
Remediation Effort |
low |
Resource |
Error Handling |
Language |
Scala |
Description
Reports an if / else if chain that ends without a final else branch, leaving the case where no condition holds unhandled.
Rationale
A chain of alternatives reads as an exhaustive classification, but without a final else the remaining case falls through silently - as an expression the chain then yields Unit rather than the value the other branches produce. Whether the omission was deliberate or an oversight is invisible to a reader and to the compiler, and it is a common source of values that go unset and of defects that surface far from this code.
The following code illustrates the pattern detected by this rule:
class IfElseChainWithoutElse {
def twoBranches(n: Int): Unit = {
// FLAGGED: if / else-if chain has no final else clause
if (n > 0) {
println("positive")
} else if (n < 0) {
println("negative")
}
}
}