Monday, November 29, 2010

if statement failure.

Looking at an if statement I noticed a problem.   This works, but is technically incorrect.

if( a == null || b==null) {
// do something
} else if( a!=null || b != null) {
// do something else
}

The intention here is really.
if( isSomeState(a,b) ) {
// do something
} else if( !isSomeState(a,b)) {
// do something else
}

which means ultimately it's looking for
(a == null || b==null)
and
!(a == null || b==null)
However !(a == null || b==null) translates into
a != null && b!=null

It happens to work by accident because if either are null the code will go into the if statement and never evaluate the else if portion, however, if the statement were to get more complex intentionally then it could cause all kinds of mistaken errors.

What if the code changed to be

if( a == null || b==null || c==null) {
// do something
} else if( a!=null || b != null) {
// do something else
}

only now the intention is 
if( isSomeState(a,b)  || c==null ) {
// do something
} else if( !isSomeState(a,b)) {
// do something else
}

What was previously be handled by the if statement is no longer handled, and the else if, will handle situations that it did not evaluate before, the something else will happen a lot more than it's supposed to.

When writing complex if statements and the else if is supposed to be the opposite state of the if, then refactor that logic into method and use the method and !method to ensure that the correct logic is used.

No comments: