Wednesday, May 16, 2012

Making Groovy scripts maintainable

Writing Groovy code is cool. Fixing them some time later can be hard as they tend to grow out off control pretty soon. Finding an install.gsh that has 100+ lines is not hard. And since Groovy is a very expressive language those 100 lines are not making the compiler happy - it's actually stuff to be done.

I have a bad feeling about this

In Java we're pretty much used to either creation of big, ugly, monolithic classes or going the completely opposite direction with Spring or some other dependency injection framework. In scripts we tend to rather go the first way which makes them unmaintainable and hard to understand. Why? Because historically shell scripts were created this way and we tend to think in this way. It's a script, isn't it?

These are not the droids you're looking for...

In fact Groovy scripts are not scripts at all. They are classes, that will have a main method. The only difference is that they are automatically compiled when needed. This means we can use all the good Java stuff when writing Groovy scripts: classes, external libraries through @Grab annotation and so on.

Here's an example:

Configuration.groovy:
class Configuration {
    String path
}
install.gsh:
#!/usr/bin/groovy

println new Configuration(path: "/tmp")

Since all the classes are in the default package (inaccessible from pure Java!) you don't need to import them manually. Should it make sense to split them into folders you can always do that:

org/example/Configuration.groovy:
package org.example

class Configuration {
    String path
}
install.gsh:
#!/usr/bin/groovy

import org.example.Configuration

println new Configuration(path: "/tmp")

Further more you can write tests for your classes, make sure they always work even if some mad cow enters the arena and goes Hulk on your code :)

May all your scripts be maintainable forever and for always!

1 comment:

Unknown said...

Very nice, this has helped me.