Why is this an issue?
An operand of a boolean expression that never changes the result of the expression might not match the programmer’s intent and can lead to
unexpected behavior and potential bugs.
Dim a = True
If a Then
DoSomething()
End If
This also applies to the null conditional operator
when one of the operands always evaluates to Nothing
.
Dim d As String = Nothing
Dim v1 = If(d, "value")
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 unnecessary operand
- to remove the unnecessary operand
Code examples
Noncompliant code example
Public Sub Sample(ByVal b As Boolean, ByVal c As Boolean)
Dim a = True
If a Then ' Noncompliant: "a" is always "true"
DoSomething()
End If
If b AndAlso a Then ' Noncompliant: "a" is always "true"
DoSomething()
End If
If c OrElse Not a Then ' Noncompliant: "Not a" is always "false"
DoSomething()
End If
Dim d As String = Nothing
Dim v1 = If(d, "value") ' Noncompliant: "d" is always Nothing and v1 is always "value".
Dim v2 = If(s, d) ' Noncompliant: "d" is always Nothing and v2 is always equal to s.
End Sub
Compliant solution
Public Sub Sample(ByVal b As Boolean, ByVal c As Boolean, ByVal s As String)
Dim a = IsAllowed()
If a Then ' Compliant
DoSomething()
End If
If b AndAlso a Then ' Compliant
DoSomething()
End If
If c OrElse Not a Then ' Compliant
DoSomething()
End If
Dim d As String = GetStringData()
Dim v1 = If(d, "value") ' Compliant
Dim v2 = If(s, d) ' Compliant
End Sub
Resources
Documentation