Two branches of a conditional have identical bodies
ID |
vbnet.correctness.duplicate_branches |
Severity |
high |
Remediation Complexity |
medium |
Remediation Risk |
medium |
Remediation Effort |
low |
Resource |
Duplicate Logic |
Language |
VB.NET |
Description
Flags a conditional whose two branches contain exactly the same statements: an If / Else
pair with identical bodies of up to three statements, or two adjacent branches of an
If / ElseIf chain with identical bodies of up to two statements. Longer bodies are not
compared, and neither are duplicated branches separated by a branch that differs. Bodies that
share only their first statement and then diverge are not reported.
Rationale
The condition that selects between the branches has no effect on what the program does, so either the code does not behave the way its shape suggests or it states the same thing twice. When one branch was meant to differ — the second amount, the other channel, a different template — the copy-paste left a real defect that is unusually hard to spot in review, because two symmetrical branches read as deliberate. When the branches genuinely are equivalent, the duplication is a maintenance liability instead: the next change has to be made in both places, and making it in only one reintroduces a difference nobody realised had been lost.
The following code illustrates the pattern detected by this rule:
Public Sub Notify(ByVal urgent As Boolean)
' FLAGGED: Two branches of a conditional have identical bodies
If urgent Then
SendEmail()
Else
SendEmail()
End If
End Sub
Remediation
Fix the branch that was meant to differ. If the branches really are equivalent, drop the condition
for an If/Else, or merge the two conditions with OrElse for an If/ElseIf chain.
' Before: both branches return the same value
If kind = 1 Then
Return "email"
ElseIf kind = 2 Then
Return "email"
End If
' After
If kind = 1 OrElse kind = 2 Then
Return "email"
End If