Mark Derricutt's Disturbing Thoughts

A Little Head Trauma...: Returning None is Evil

posted Thursday, 22 November 2007

Via Cedric's blog I came upon Marty Alchin's post on the perils of returning None or Null from your methods:

That is, of course, until you try to use your shiny, newly-retrieved object. Java then falls over itself and dies a horrifically painful death upon realizing that you dared try to do anything with null. This is the NullPointerException, and it's exceptionally (pun intended) difficult to track down. You see, the traceback only tells you where your code tried to reference some property or method of null. What you really want to find out is where did that null come from? [From A Little Head Trauma...: Returning None is Evil]

As I was reading through the post, its comments, Cedric's rebuttal and its own series of comments I was reminded of how Smalltalk deals with this - closures.

(self doSomethingThatMightReturnNil)
  ifNotNil: [val | val doSomethingWithNoHassle].

Here, the message doSomethingThatMightReturnNil will return either a valid object instance, or an singleton instance of the Nil class. Under Smalltalk, every object has the messages ifNil: and ifNotNil: which will execute the provide block/closure if the instance is, or isn't nil (the Nil object simply does the opposite).

One of the best things I love about this approach is that the ifNotNil: message passes the instance into the block as a variable which saves having to a store any temporary variables, or simply repeating the call or a variation of it. Using this method also leaves exceptions to do what exceptions are meant for: exceptional problems.

tags:      

links: digg this    del.icio.us    technorati    reddit




1. Sam Shuster left...
Friday, 23 November 2007 3:30 pm

One note. You said "Under Smalltalk, every object has the messages ifNil: and ifNotNil:" That is in effect true, but may leave a wrong impression for those not familiar with Smalltalk. In fact, the class Object defines these messages, as does UndefinedObject (the class that represents the singleton instance of the object named nil (lower case 'n').

All normal classes inherit from Object, and thus respond to ifNil: and ifNotNil:. The effect is indeed that all objects then act as if every object has these messages.

The exceptions to this inheritance are for object proxies and other very special circumstances that are really way beyond the scope of a simple comment


2. Bob Hutchison left...
Friday, 23 November 2007 4:13 pm :: http://recursive.ca/hutch/

Hi,

Nice post. It sparked a brief flash of Smalltalk envy. I posted a Ruby 'enhancment' on my blog (http://recursive.ca/hutch/2007/11/22/a-little-unne cessary-smalltalk-envy/') that looks a lot like your Smalltalk code

Bob