A New First: Being Asked to Not Use Boolean Algebra

Crazy Lemon the Coder

Today I had the very uncomfortable first of a co-worker coming up to me and telling me that they couldn't understand the code I'd written. It contained boolean algebra, and while it's not as easy as '1 + 1', it's not a lot harder to anyone that's been actually trained in the field of programming.

The code in question was using bit-mapped flags like the following:

  public static long ERROR_404          = (1 << 0);
  public static long ERROR_408          = (1 << 1);
  public static long ERROR_500          = (1 << 2);
  public static long CONNECTION_REFUSED = (1 << 3);
 
  // set up which errors you don't want to log
  long  ignoreErrs = ERROR_404 | CONNECTION_REFUSED;
 
  try {
    // ...snip...
  } catch (FileNotFoundException fnfe) {
    if ((ignoreErrs & ERROR_404) == 0) {
      log.error("Got an Error 404 (FileNotFoundException)!");
    }
  }

where it's clear that we don't need a full integer for each of the errors I wish to not log. Just a bit. Which makes perfect sense - so long as the number of errors you're trapping for are less than the bits in a Java long datatype. But in our case, it was jsut fine - I think we had a total of five errors to look for.

So my co-worker was clearly flustered about the code that allowed for the selective logging of each error type. They didn't understand that the code snippet:

  if ((bunchOfFlags & aMask) != 0) {
    // ...blah...
  }

is just saying: "If the aMask bit is set in the bunchOfFlags". It's a simple true/false condition, that (unfortunately) Java won't allow to be written:

  (bunchOfFlags & aMask)

because it says it can't compare a long to a boolean. Ugh... OK, fine. I'll put in the == 0 and Java will be happy. Still... I'll admit it's a little trickier when you're working with "negative logic" like what errors not to log, but really... is it all that hard?

Clearly, the answer is Yes for this person.

So I spent some time today, and I'm sure I'll need to finish it up in the morning because the big motivation for this level of control over the logging is my belief that errors in the log of any application should be a call to action and not "noise". Unfortunately, this isn't universally agreed in the group, and we have people that want to see errors that they have no intention of putting a halt to, where as I want that particular noise eliminated.

But being asked to remove boolean algebra from my code... that's a first. Amazing.