Bit operation against an identity operand leaves the value unchanged
ID |
vbnet.maintainability.no_unnecessary_bit_operation |
Severity |
critical |
Remediation Complexity |
trivial |
Remediation Risk |
low |
Remediation Effort |
low |
Resource |
Dead Code |
Language |
VB.NET |
Description
Reports a bitwise operation whose constant operand is the identity for that operator and so
cannot change the result: And -1, Or 0, Xor 0, << 0 and >> 0.
Rationale
Each of these operands is the neutral element of its operator - every bit of -1 is set, 0
sets no bits, and a shift of zero positions moves nothing - so the expression evaluates to its
other operand and the operation is dead. It is almost never written deliberately. Typically the
constant is a mask, flag or shift width that came from a named constant left at its default
value, from a computed value that turned out to be 0, or from a copy of a neighbouring line
whose constant was never adjusted. The code then reads as though it masks, merges or shifts,
while the value passes through untouched - so the mask that was supposed to strip the high bits
never strips them, and the defect surfaces later as a value out of range or a flag that is
never cleared.
The following code illustrates the pattern detected by this rule:
Public Function ClampChannel(ByVal channel As Integer) As Integer
' FLAGGED: Bit operation against an identity operand leaves the value unchanged
Return channel And -1
End Function
Remediation
Decide which was intended and make it explicit: if the operation is genuinely redundant, delete it and use the operand directly; if a real mask, flag or shift width was meant, supply it, preferably as a named constant so the intent is stated once and reused.
' Before: reads as a mask, changes nothing
Return channel And -1
' After: either drop the operation ...
Return channel
' ... or apply the mask that was actually intended
Private Const ChannelMask As Integer = &HFF
Return channel And ChannelMask