mercoledì 3 luglio 2013

Do you like booleans?

Booleans: you love them or you hate them.
Personally, I hate them.
What is wrong with booleans? Nothing, except that they are often used in the wrong way.
A boolean (that is a condition that is either true or false) can be used only to test a single, autonomous condition. The key word here is "autonomous": the boolean can indicate only one truth at a time.
And developers, of course, know the truth!
So you can end up with some code like the following:

void foo( boolean conditionA, boolean conditionB ){

  if ( conditionA ){ doA(); }
  else if ( conditionB ){ doB(); }
  else doPanic();

}


that is working fine until conditionA and conditionB are totally indipendent. That means not only that a value affects the other, but also that there must be no priority between conditionA and conditionB.
To better understand, suppose that there is a new constraint that imposes that whener conditionA is false, conditionB cannot be true too. Therefore the code becomes:


void foo( boolean conditionA, boolean conditionB ){
  if ( ! conditionA )
    conditionB = false;

  if ( conditionA ){ doA(); }
  else if ( conditionB ){ doB(); }
  else doPanic();

}

Due to the above constraint, there is now a less number of cases:
  • case 1: conditionA = true and conditionB = true;
  • case 2: conditionA = false and conditionB = false;
  • case 3: conditionA = true and conditionB = false.

So there are now three possible cases out of four using two booleans.
Sooner or later, you will miss some check against the possible values and your code, by the way, will result difficult to read. Consider someone who wants to use your API and that has access only to the prototype of the code:

void foo( boolean conditionA, boolean conditionB )

You have to clearly mantain the documentation explaining that the case {false, true} cannot be applied.
So what is the solution?
Instead of having to deal with not-so-boolean booleans, consider using other way of representing a finite, well know, set of possibilities, like enumerations or "old-style" hex variables. They will make your code cleaner and easier to read, and will scale once you have to introduce new constraints.

Nessun commento: