Condition is always True or always False
ID |
vbnet.correctness.condition_always_true |
Severity |
high |
Remediation Complexity |
medium |
Remediation Risk |
medium |
Remediation Effort |
low |
Resource |
Control Flow |
Language |
VB.NET |
Description
Flags an If or ElseIf whose condition is a constant written in the source: the literal
forms If True Then and If False Then, and expressions that fold to a literal such as
If Not False Then. Only a literal condition is reported. A condition on a variable is never
reported, even when the variable is assigned a constant a few lines earlier and never
reassigned, because deciding that safely needs flow analysis this rule deliberately does not
do — a flag can be reassigned in a nested block, in a Catch, or through a ByRef argument
without the assignment being visible at the test. While True loops are also left alone: an
unconditional loop is an idiom, not a mistaken condition.
Rationale
A condition with a fixed outcome means one side of the branch can never run: an always-True
test makes the Else dead, an always-False test makes the body dead. The code still reads as
though a decision were being made, so a reviewer credits the program with behaviour it does
not have — the fallback path is never exercised, the feature is permanently on or permanently
off. Debug switches and feature flags hard-wired during development are the common source, and
they survive precisely because nothing fails: the program keeps working while one entire path
goes untaken, often for the whole life of the release.
The following code illustrates the pattern detected by this rule:
Public Sub Publish(ByVal draft As Boolean)
' FLAGGED: Condition is always True or always False
If True Then
Save()
Else
Discard()
End If
End Sub
Remediation
Restore the condition that was meant to be tested, or remove the test together with the branch that can never run.
' Before: a hard-wired literal makes the Else unreachable
Public Sub Export()
If True Then
CompressAndWrite()
Else
Write()
End If
End Sub
' After: the decision belongs to the caller
Public Sub Export(ByVal useCompression As Boolean)
If useCompression Then
CompressAndWrite()
Else
Write()
End If
End Sub