If … ElseIf chain has no Else clause
ID |
vbnet.maintainability.else_if_needs_else |
Severity |
high |
Remediation Complexity |
trivial |
Remediation Risk |
low |
Remediation Effort |
low |
Resource |
Control Flow |
Language |
VB.NET |
Description
Reports an If … ElseIf chain that ends without an Else clause. A chain of conditions with
no final Else leaves the case where none of the conditions holds completely unhandled. A plain
If … Then with no ElseIf is not reported - a single guarded action legitimately does nothing
when its condition is false.
Rationale
Once a chain enumerates alternatives, the reader has to decide whether the missing Else is
deliberate or an oversight, and nothing in the code answers that. At run time the unhandled case
is silent: the variable being assigned keeps whatever value it already had, or the function falls
through and returns the type default, and the caller cannot tell that from a real result. This is
the classic failure when a new enum member, region code or status is introduced later and this
chain is not updated.
The following code illustrates the pattern detected by this rule:
Public Function SurchargeFor(ByVal region As String) As Decimal
Dim surcharge As Decimal = 0D
' FLAGGED: If ... ElseIf chain has no Else clause
If region = "EU" Then
surcharge = 4.5D
ElseIf region = "US" Then
surcharge = 6.25D
End If
Return surcharge
End Function
Remediation
Add a final Else that handles the remaining values explicitly - assign a documented default,
log, or throw (for example ArgumentOutOfRangeException) so an unforeseen value fails loudly
instead of being ignored. If the chain tests a single value against many alternatives, a
Select Case with a Case Else expresses the same intent more clearly.
' Before: an unknown region silently yields 0
Dim surcharge As Decimal = 0D
If region = "EU" Then
surcharge = 4.5D
ElseIf region = "US" Then
surcharge = 6.25D
End If
' After: the unhandled case is explicit
Dim surcharge As Decimal
If region = "EU" Then
surcharge = 4.5D
ElseIf region = "US" Then
surcharge = 6.25D
Else
Throw New ArgumentOutOfRangeException(NameOf(region))
End If