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.
