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 | 0 Comments

Typo problems, new site coming soon (hopefully)

December 13, 2006

This site is currently using Typo, which is blog software written using Ruby on Rails(RoR). It uses Mongrel to run RoR. Apache is the actual web server, it passes requests intended for RoR to mongrel, which then serves the request.

I originally started this site with WordPress, which is PHP-based blog software. I'm not a big fan of developing with PHP, and I was hoping to start doing some custom things with my site, so I switched to Typo, so that my site would be running RoR, and I could make my own extensions using RoR.

Since then, I've discovered a few major design flaws with RoR, so I'm not writing any code in RoR now. First of all, and this isn't really a design flaw, but more of a bug, is that some combination of Typo, Mongrel and Rails is causing a serious memory leak. Typo has caused my entire VPS instance hosted at VPSLand to become unreachable. This has caused this site to be down over the past few days. I've never had that kind of problem with a Java app.

Aside form the memory leak issues, and general difficult of setting up a stable rails site, the biggest thing I don't like about RoR is that your application model is inferred from the database at runtime. I'd much prefer it the other way around, where I write a domain model in code, and then the framework generates the database for me.

The reason why it isn't like this in RoR is because Ruby isn't a statically typed language. There has been a lot of hype around dynamically typed languages, but I think they have disadvantages as well. Since I can't create a class in Ruby and declare what type each property is, there is no way to automatically generate a database based on the model.

This is what got me interested in Django. Django is another web framework, but based on Python instead of Ruby. Python and Ruby are both dynamically typed languages, similar in a lot of ways, but they also have their differences. With the Django project, they chose to create pseudo-typing within Python, where you define the type of property of an object in a way that the framework understands it, but not the Python language itself.

I like Python and Django, but I always thought to myself, wouldn't it be nice if the language was optionally typed, to that you could declare the type if you want to, so that the type could be used as metadata by a framework?

I do most of my programming in Java, so I came to the realization that there are great things about Python, Django, Ruby and Rails, but Java, Stripes, Hibernate and friends have advantages too. I decided that although Python/Django and RoR (less so RoR, in my opinion) certainly seem like great ways to build web apps, I don't think there's an order of magnitude increase in productivity over Java, as some have claimed.

But when turning back to Java, one thing I realized I missed was the true object oriented-ness that dynamic langauges allow. For example, in dynamic languages, to store a user object in the database, you use user.save, whereas in Java, you do something like userDao.save(user). Also, the succinctness of the dynamic languages are great, whereas Java verbosity can be almost ridiculous at times. Try this one on for size:

private static final List<Map<String, Date>> DAYS =
    new ArrayList<Map<String,Date>>();
static {
    try {
        Map<String,Date> map = new HashMap<String,Date>();
        map.put("Pearl Harbor",
            new SimpleDateFormat("MM/dd/yyyy").parse("12/07/1941"));
        DAYS.add(map);
        map = new HashMap<String,Date>();
        map.put("Iwo Jima",
            new SimpleDateFormat("MM/dd/yyyy").parse("02/19/1945"));
        DAYS.add(map);
    } catch(ParseException ex) {
        ex.printStackTrace();
    }
}

public static void main(String[] args) {
    for(Map<String,Date> day: DAYS) {
        for(Map.Entry<String,Date> e: day.entrySet()) {
            System.out.println(e.getKey()+", "+e.getValue());
        }
    }
}

And then in a yet-to-be-discussed dynamic language:

def days = [ 
  'Pearl Harbor' : new java.util.Date('12/7/1941'),
  'Iwo Jima' : new java.util.Date('2/19/1945')
]
days.each { key, value -> println "$key, $value" }

So, wouldn't it be nice if there was a dynamic, optionally typed language that would allow us to build a really great, object-oriented web application framework with a syntax as succinct as the syntax of fully dynamically typed languages? Well, there is, and it is Grails.

Grails is a web-framework based on Groovy. Groovy is a scripting language that runs in the Java VM. It complies to Java bytecode. This is nice because you can build web apps using Groovy on Grails (GoG?), and then deploy to a regular Java application server, such as my personal favorite, Resin.

The other nice thing about Grails is that it leverages all the existing Java frameworks, such as Spring and Hibernate. It puts a nice domain specific language on top of hibernate to make using Hibernate even easier.

I'm just getting my feet wet learning Grails, and the best move I've made so far is to purchase the e-book version of The Definitive Guide to Grails. I've found the documentation on the grails site to be ok, but the book is great. It's a must read for anyone looking into Grails. My only criticism of the book so far is that they may have published it a little to early, because for example if states that Grails doesn't support many-to-many relationships, when in fact it does as of version 0.3.

So the point of this long technical discussion is that from what I've read about Grails so far, it looks interesting. I'm going to try to get a new version of this site developed with Grails, and I'll try to make posts here of my progress, assuming Typo doesn't bring down my site again.

Posted in Technology | Tags Django, Python, Ruby, Grails, Java, Rails | 2 Comments