Both operands of a binary operator are identical

ID

vbnet.correctness.identical_operands

Severity

high

Remediation Complexity

trivial

Remediation Risk

low

Remediation Effort

low

Resource

Redundant Operation

Language

VB.NET

Description

Flags a binary operator whose two operands are the same expression: x AndAlso x, x OrElse x, x And x, x Or x, x - x, x / x, x \ x, x Mod x, x Xor x, and the comparisons x <> x, x > x, x < x, x >= x and x ⇐ x. Since = also means assignment in VB.NET, the equality form is reported only where the context makes it a comparison, namely an If …​ Then condition or a Return. Operators for which repeating an operand is meaningful are deliberately out of scope: side * side squares, side + side doubles and text & text concatenates.

Rationale

With both operands identical the operator contributes nothing. The logical forms collapse to the operand itself, the comparisons are constant (x >= x is always True, x <> x always False) and the arithmetic forms have fixed results (x - x and x Mod x are zero, x \ x is one, or throws when the operand is zero). Nothing in the build complains, so the check the author believed they were writing simply is not there: a range guard that only ever tests its lower bound, a change detector that never reports a change, a flag test that is always satisfied. The surrounding code then behaves as if the missing second condition had been written and had passed — the case a test suite is least likely to cover.

The following code illustrates the pattern detected by this rule:

Public Function InRange(ByVal value As Integer, ByVal upper As Integer) As Boolean
    ' FLAGGED: Both operands of a binary operator are identical
    If value > 0 AndAlso value > 0 Then
        Return True
    End If
    Return False
End Function

Remediation

Replace the repeated operand with the variable, field or bound that was intended. Drop the expression altogether if its constant result is what you actually want.

' Before: the second operand repeats the first, so `upper` is never checked
Return value > 0 AndAlso value > 0

' After
Return value > 0 AndAlso value < upper

Configuration

This detector does not need any configuration.