CodeSOD: Flexing Bits

In the mid-00s, famous Web plugin Flash tried to make a pivot. It wasn't going to be for games or little animations anymore, it was going to be for Enterprise Applications, and they called it Flex.

Flex was a pile of XML files and ActionScript which would be compiled together into a Flash-based UI that would work in every browser (with the Flash plugin). This was a terrible idea to begin with, and was basically killed pretty quickly by Apple releasing the iPhone without Flash, but for a brief moment, it was a product people used. It's was "donated" to Apache in 2012, as what I can only assume was a White Elephant.

But in 2008, the SDK went open source. And it's from this era that today's sample from Steven comes.

Steven was trawling through the SDK trying to understand why performance was bad. While this method wasn't the thing killing performance, but it was called everywhere, and left Steven scratching his head.

public static function update(flags:uint, flagMask:uint, value:Boolean):uint { if (value) { if ((flags & flagMask) == flagMask) return flags; // Nothing to change // Don't use ^ since flagMask could be a combination of multiple flags flags |= flagMask; } else { if ((flags & flagMask) == 0) return flags; // Nothing to change // Don't use ^ since flagMask could be a combination of multiple flags flags &= ~flagMask; } return flags; }

This very clearly named update method has two branches. If the clearly named value is true, we check if flags & flagMask is the same value as flagMask, which… only happens if flags and flagMask are the same value. Regardless, if that's the case, we can just return flags, otherwise we |= it with the mask.

But, if value is false, we check instead if flags and flagMask have no overlap. If they don't, then no update happens, but if they do, we flags &= ~flagMask, which will set the overlapping bits to zero.

So update is a method that either adds bits to a mask, or removes bits from a mask. This is information you don't get from the method name, and honestly don't really get from the parameters either. The guards against mutating unnecessarily may or may not be an optimization- given how ActionScript works, they might be avoiding creating a new integer and thus triggering some future garbage collection.

But, a cryptic method signature that implements a simple operation in the least readable way possible, and is called from all over the framework for reasons that aren't clear when reading the code. It's everything I expect from a Flash UI framework.

[Advertisement] ProGet’s got you covered with security and access controls on your NuGet feeds. Learn more.

This post originally appeared on The Daily WTF.

Leave a Reply

Your email address will not be published.