Friday, May 11, 2007

Truth, Justice, And The American Way

There's one subtle feature of some languages that keeps causing me pain and in the wrong hands causes more harm than good. What is this feature? Let me show you some Javascript code:

if (transaction.amount) {
transaction.markValid();
} else {
transaction.markInvalid();
}

Nothing wrong here, from the looks of it the code is checking if the transaction has an amount defined and then marks the transaction valid or invalid. Simple right? But, what if an amount is defined and it is zero? You would think the transaction is marked valid right? WRONG! It will be marked invalid because anything that's zero, nil, or undefined in Javascript is considered false.

And that's my beef, why not treat booleans with their own type. Why treat any other value as equivalent? Subtle bugs like the one above are infuriating to me. The simple reason is that they can easily be avoided with a few extra characters.

if (transaction.amount == undefined) {
transaction.markValid();
} else {
transaction.markInvalid();
}

The moral of this story is to code exactly what you mean. Be specific. Don't rely on arcane language features to save a few key strokes. Java and Smalltalk do the right thing and make you use boolean types.

No comments: