Why is this an issue?
Conditional expressions which are always true
or false
can lead to unreachable code.
In the case below, the call of Dispose()
never happens.
Dim a = False
If a Then
Dispose() ' Never reached
End If
Exceptions
This rule will not raise an issue in either of these cases:
- When the condition is a single
const bool
Const debug = False
'...
If debug Then
' Print something
End If
- When the condition is the literal
true
or false
.
In these cases, it is obvious the code is as intended.
How to fix it
The conditions should be reviewed to decide whether:
- to update the condition or
- to remove the condition.
Code examples
Noncompliant code example
Public Sub Sample(ByVal b As Boolean)
Dim a = False
If a Then ' Noncompliant: The true branch is never reached
DoSomething() ' Never reached
End If
If Not a OrElse b Then ' Noncompliant: "not a" is always "True" and the false branch is never reached
DoSomething()
Else
DoSomethingElse() ' Never reached
End If
Dim c = "xxx"
Dim res = If(c, "value") ' Noncompliant: d is always not Nothing, "value" is never used
End Sub
Compliant solution
Public Sub Sample(ByVal b As Boolean)
Dim a = False
If Foo(a) Then ' Condition was updated
DoSomething()
End If
If b Then ' Parts of the condition were removed.
DoSomething()
Else
DoSomethingElse()
End If
Dim c = "xxx"
Dim res = c ' "value" was removed
End Sub
Resources
Documentation