Article 3QB8M CodeSOD: Return of the Mask

CodeSOD: Return of the Mask

by
Remy Porter
from The Daily WTF on (#3QB8M)

Sometimes, you learn something new, and you suddenly start seeing it show up anywhere. The Baader-Meinhof Phenomenon is the name for that. Sometimes, you see one kind of bad code, and the same kind of bad code starts showing up everywhere. Yesterday we saw a nasty attempt to use bitmasks in a loop.

Today, we have Michele's contribution, of a strange way of interacting with bitmasks. The culprit behind this code was a previous PLC programmer, even if this code wasn't running straight on the PLC.

public static bool DecodeBitmask(int data, int bitIndex){ var value = data.ToString(); var padding = value.PadLeft(8, '0'); return padding[bitIndex] == '1';}

Take a close look at the parameters there- data is an int. That's about what you'd expect here" but then we call data.ToString() which is where things start to break down. We pad that string out to 8 characters, and then check and see if a '1' happens to be in the spot we're checking.

This, of course, defeats the entire purpose and elegance of bit masks, and worse, doesn't end up being any more readable. Passing a number like 2 isn't going to return true for any index.

Why does this work this way?

Well, let's say you wanted a bitmask in the form 0b00000111. You might say, "well, that's a 7". What Michele's predecssor said was, "that's text" "00000111". But the point of bitmasks is to use an int to pass data around, so this developer went ahead on and turned "00000111" into an integer by simply parsing it, creating the integer 111. But there's no possibly way to check if a certain digit is 1 or not, so we have to convert it back into a string to check the bitmask.

Unfortunately, the software is so fragile and unreliable that no one is willing to let the developers make any changes beyond "it's on fire, put it out".

proget-icon.png [Advertisement] ProGet supports your applications, Docker containers, and third-party packages, allowing you to enforce quality standards across all components. Download and see how! TheDailyWtf?d=yIl2AUoC8zAv7ZJokXyO1Q
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