Same condition tested twice in one if / else-if chain
ID |
scala.correctness.duplicate_conditions |
Severity |
low |
Remediation Complexity |
medium |
Remediation Risk |
medium |
Remediation Effort |
low |
Resource |
Duplicate Logic |
Language |
Scala |
Description
Reports an if / else if chain in which the same condition expression appears in two of its branches.
Rationale
The earlier branch always wins, so the body of the repeated branch can never run - it is dead code that a reader will nonetheless take for a live case. The pattern comes from copying a branch and editing the body but forgetting the condition, which means the case the second branch was written for is silently not handled at all.
The following code illustrates the pattern detected by this rule:
class DuplicateConditions {
def classify(n: Int): String = {
// FLAGGED: Same condition tested twice in one if / else-if chain
if (n > 0) {
"positive"
} else if (n > 0) {
"still positive"
} else {
"other"
}
}
}