Control flow constructs like if
-statements allow the programmer to direct the flow of a program depending on a boolean expression.
However, if the condition is always true or always false, only one of the branches will ever be executed. In that case, the control flow construct and
the condition no longer serve a purpose; they become gratuitous.
What is the potential impact?
The presence of gratuitous conditions can indicate a logical error. For example, the programmer intended to have the program branch into
different paths but made a mistake when formulating the branching condition. In this case, this issue might result in a bug and thus affect the
reliability of the application. For instance, it might lead to the computation of incorrect results.
Additionally, gratuitous conditions and control flow constructs introduce unnecessary complexity. The source code becomes harder to understand, and
thus, the application becomes more difficult to maintain.
This rule looks for operands of a boolean expression never changing the result of the expression. It 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.