Repeated condition in an If / ElseIf chain
ID |
vbnet.correctness.duplicate_conditions |
Severity |
high |
Remediation Complexity |
medium |
Remediation Risk |
medium |
Remediation Effort |
low |
Resource |
Duplicate Logic |
Language |
VB.NET |
Description
Flags an If / ElseIf chain in which two branches test the same condition, whether the
repeat is the very next branch or sits two or three branches further down the chain. The same
condition appearing in two separate, consecutive If statements is not reported: each
statement is evaluated on its own, so both bodies can run.
Rationale
Only the first matching branch of a chain runs, so a repeated condition makes the later branch
unreachable — its body is dead code no input can ever execute, however correct it looks. The
usual cause is a branch copied and pasted with the body edited but the condition left alone,
which means the case the new branch was meant to handle silently falls through to whatever
comes next: a trailing Else, or nothing at all. A shipping table that skips a weight band or
a lookup that returns the wrong zone is the kind of defect this leaves behind, and reading the
chain top to bottom rarely makes it obvious, because each branch looks reasonable in
isolation.
The following code illustrates the pattern detected by this rule:
Public Function RateFor(ByVal weight As Integer) As Decimal
' FLAGGED: Repeated condition in an If / ElseIf chain
If weight > 20 Then
Return 12.5D
ElseIf weight > 20 Then
Return 8D
End If
Return 5D
End Function
Remediation
Change the repeated condition to the case it was meant to test, or delete the branch when it is genuinely redundant.
' Before: the second branch can never run
If weight > 20 Then
Return 12.5D
ElseIf weight > 20 Then
Return 8D
End If
' After
If weight > 20 Then
Return 12.5D
ElseIf weight > 5 Then
Return 8D
End If