Thursday, April 17, 2008

grails and the nulls that confuse me

Recently I've started doing a lot of my work in groovy. Being an old fart I love my java, but many of the young guys are pushing me to pick up the dynamic languages of the times. I'm not a fan of Ruby (mostly due to the community, you know who) and while I like Python it just doesn't fit for scalable enterprise systems.

Then I noticed groovy, and I love it. I have all the power of java with the syntactical candy of dynamic languages. And Grails is really awesome (especially the 1.x series). Its like Ruby on Rails, but made by people who really want to use it in production. I can write groovy code, and use hibernate, and run on top of a clustered Jetty with terracotta, how cool is that?

I do have to say, its the little things that get you. A good example is GORM and exception handling. In EJB3 or even straight hibernate, when I save an object that doesn't validate I'll get a java.lang.RuntimeException. Example


Person p = new Person();
p.setName("something Bad);
entityManager.persst(p);

If for some reason p isn't able to be saved by the entity manager a runtime exception will be thrown. Being a seasoned EJB developer I'd use this exception to my advantage and let it trickle out to the container and roll back the managed transaction (I think this is beautiful, but I guess a thing of the past).


Groovy, grails, and even rails does this different. The way you know an entity is saved is by the return value on the entity.save() method. Lets use the example above in grails.


def p = new Person(name:"something bad")
p.save()


if for some reason p is unable to be saved we won't be notified by the above code, you actually have to do it like this:


def p = new Person(name:"something bad")
if ( !p.save()) { p.errors.each(log.error(it))}


What I find fascinating about this example is a statically typed language is actually less code than a dynamic one!

2 comments:

Anonymous said...

with
p.save(flush:true)
you may get your exception

Anonymous said...

If your statically typed language is not one of the boilerplate languages like Java, C++, etc., then you'll find the statically typed language shorter quite often. And more reliable and faster and easier to understand.

Scala and Haskell are both good candidates for this.