Mar 14 2007

Good Coding: Avoid Negative Logic Tests

I recently encountered the following code in a project I’m maintaining that illustrates why it’s dangerous to use negative tests:


 unless ( $foo xor $bar ) {
     print_error( "You can only have one or the other defined\n" );
 }

Set aside the fact that the error message stinks, and look at the logic.

The xor function evaluates to true if, and only if, one or the other value passed to it is true. Otherwise it is false.

Here’s a table to illustrate the concept:

Input 1 Input 2 Result of xor
1 1 0
1 0 1
0 1 1
0 0 0

In the code above, you will get the error message You can only have one or the other defined when you pass in two undefined or “0” values.

Clearly, this isn’t what the original developer had intended.

I converted the code into a positive logic test, which makes it much clearer, even with the terrible error message:


 if ( $foo && $bar ) {
     print_error( "You can only have one or the other defined\n" );
 }

I recommend avoiding negative logic tests as much as possible. If you must use one, make sure you have a really good reason and put that reason in a comment for future developers.

  1. Nice tip!!

    Have you tried different programming languages? I work in Java but anyway your tip was useful to explain something.

    Greets from Ecuador.


    Gerson    Sep 18, 02:57 PM    #
  2. Thanks Gerson!

    I’ve programmed in many languages over the years: Scheme, Prolog, C/C++, PHP, Basic, and Perl (of course).

    Glad the tip helped you out!


    Tara    Sep 18, 03:02 PM    #

Add a Comment

  Textile Help

<< Good Coding: My Top 5 Pet Peeves

Evolution Mail - Today's Accidental Discovery >>