Article 6C7Z7 CodeSOD: VBitMask6

CodeSOD: VBitMask6

by
Remy Porter
from The Daily WTF on (#6C7Z7)

Bitwise operations are one of those things that experienced developers find easy (if not intuitive), but are a fairly bad way to expose functionality without real careful design. After all, flags & 0x02 doesn't really mean much if you don't know what 0x02 is supposed to represent.

But with named constants and careful thought, a bitmask can be a great way to pass flags around. At least, they can be if you understand how to use your language's bitwise operators.

If you don't, then you end up writing this code, which Rensuka found many years ago.

 Dim bit(8) As Boolean 'Determin which bits need to be turned on If ... Then bit(1) = True ElseIf ... Then bit(2) = True ElseIf ... Then bit(3) = True ... ElseIf ... Then bit(8) = True End If

This is VB6, and while bitwise operations can get weird in VB6 (only the Byte type is unsigned), VB6 absolutely has bitwise operators. In fact, VB6 even has the Imp operator, or "implication"- which is a common logical operation but one rarely implemented as a bitwise operator.

So this developer could have done this via bitmasks, but instead chose an array of Booleans. And that's awful, but that's not the WTF. Because look at how they use the bitmask.

 Dim counter As Integer Dim i As Integer 'Count all the bits we turned on For i = 0 To UBound(bit) counter = counter + 1 Next i If counter = 0 Then 'Do stuff, etc. ElseIf counter = 1 Then 'Do stuff, etc. ElseIf counter = 2 Then 'Do stuff, etc. ElseIf counter = 3 Then ... End If

They don't use it as a bitmask at all! There's a hint here that once upon a time it was attempting to count the number of true flags, and that would be a WTF: you go through all the work to set up a bitmask when you could just look at a sum.

But even that's gone- here, counter just gets incremented once for each item in the array. You could just get rid of all of this code and execute whatever is in the final ElseIf condition.

I want to think that perhaps this code once used to actually do something a bit more than it does, but I suspect that the developer maybe wandered through a few pathways, but this was the first working version of the code. There's no good reason for anything to be like this, yet here it is.

otter-icon.png [Advertisement] Continuously monitor your servers for configuration changes, and report when there's configuration drift. Get started with Otter today!
External Content
Source RSS or Atom Feed
Feed Location http://syndication.thedailywtf.com/TheDailyWtf
Feed Title The Daily WTF
Feed Link http://thedailywtf.com/
Reply 0 comments