venerdì 16 settembre 2011

Avoid Booleans!

Booleans are a tempting thing introduced with modern languages, and that have been always emulated in ancient languages. After all, who haven't written at least once a couple of C macros like the followings?

 #define TRUE  1
 #define FALSE 0

A lot of libraries, including GNU, defines them too!
The problem with booleans is that they can easily become a source of mess, making the code a lot less readable and understandable. Of course booleans are easy to understand when they are used as conditionals, such as in if, while, do-while, and so on, but they can hide a lot of behaviour when they are placed as arguments in method calls. To start with a simple example, consider the following method call:

  createNewFileOverwriting( "/tmp/blog.txt", true );

What does the method do? Well, we can expect that the method will create a new file overwriting it if the file already exists. Only a good documentation can say what that "true" really means. But what if the method call was:

  createNewFile( "/tmp/blog.txt", true );

Less clear to understand, huh? Here the "true" could mean "overwrite the file if it exists", or "create the directory if it does not exists", or something else. There are also worst examples:

    repaint( false );

What does it mean? That it should not execute repaint? Most probably that it should not repaint immediatly, but as soon as possible. In this case a more comprensive method name would help:

    repaintImmediatly( false );

The above are just simple examples, but libraries are full of such conditions. How can the above code be improved? Simply by creating constants with meaningful names, substituting booleans with enumerations. Now read the code that follows and consider if it is clearer to understand that the above examples:


   repaint( REPAINT_IMMEDIATLY );   // corresponds to repaint( true );
   repaint( REPAINT_LAZY );            // corresponds to repaint( false );
   createNewFile( "/tmp/blog.txt", 
          CREATE_DIRECTORY_IF_NOT_EXISTS | OVERWRITE_FILE_IF_EXISTS );               

So with a little extra typing you can produce code that is really much clear to read and to understand, and therefore to mantain.

Nessun commento: