Tuesday, November 17, 2009

Random bits: xor in the enterprise

You rarely find useful applications of xor (or any other bitwise operator for that matter) in everyday enterprise software development. Sure, they are widely used when implementing non-trivial algorithms... hell, even the trivial ones if they aren't concerned with the calculation of a total gross premium after a second endorsement on a rainy evening.
Anyway, I was pleasantly surprised after I found this little method:

void process(SomeData first, SomeData second) {
if (first == null && second == null) {
doWhenBothNull();
} else if (first != null ^ second != null) {
doWhenOneNull();
} else {
doWhenBothNonNull();
}
}

Of course this code could have been rewritten without using xor and wouldn't loose in readability; of course, the whole algorithm could have been rewritten so that these checks wouldn't even take place.
This post isn't about maintainability or good practices. It is about the small things that make our work worthwile.