Please join me at my new location bryankyle.com

Monday, October 11, 2010

Nil Advice

Recently I wrote that one of the things I really like about Objective-C is how it handles nil-values when calling methods. It certainly makes for code that's easier to read however it does have a downside as mentioned by Daniel Jalkut of Red Sweater software. In Don't Coddle Your Code, Daniel writes:

It s also worth noting that LaMarche s defense of nil ing out instance variables hinges on the presumption that messaging nil is safe. True, messaging nil will not cause a crash. But is that safe? Not if it changes the behavior of your code in unpredictable ways.

He goes on to demonstrate his point with some contrived but applicable code:

if ([mDiplomat didReturnGestureOfPeace] == NO)
{
    [[NuclearWarehouse nuclearMissile] launch];
}

Daniel's point is this:

The biggest disservice you can do to your users is to allow them to run code that has unpredictable behavior. The whole point of programming is to make computers accomplish tasks in predictable ways.

I think he makes an excellent point. To paraphrase -- and I'm sure C++ developers will agree -- just because you can do something doesn't mean that you should. This language feature is a boon for those that understand how to use it effectively and design interfaces that work well with it.