The Death of the NullPointerException

December 16, 2006

In Chapter 4 of The Definitive Guide to Grails, which I will now coin with an acronym soon to be ubitqious among grailers, DGG, there is this code snippet:

class BookmarkController {

    def scaffold = Bookmark

    def save = {
        def b = new Bookmark(params)
        if( ['http', 'https'].contains( b.url?.protocol ) ) {
            // save bookmark
            ...
        } else {
            flash.message = 'Invalid bookmark'
            redirect(action:create)
        }
    }
}

This is showing how you can use scaffolding, but override one method, without having to throw away the whole scaffold. That is nice, but this is the greatest:

Note the usage of Groovy’s safe dereference operator to safeguard against the infamous NullPointerException. The expression b.url?.protocol will essentially evaluate the whole expression as null when the url property is null instead of throwing a NullPointerException. It is quite remarkable what a huge difference this one operator makes, not only to the length of your code, but to the quality, simply by dramatically reducing the amount of null checking the programmer is required to perform.

Alleluia, Praise Jesus, Amen. My only complaint is that I don't see this mentioned anywhere in Groovy's documentation.

From messing around with in in the console, it appears that you have to put the ? on the end of each property that could be null. In the example above, "b" is always guaranteed to be non-null, but for example, if it wasn't, you need to do:

b?.url?.protocol     

Posted in Technology | Tags Grails

Comments Disabled