I find myself nowadays mixing a lot of JVM languages: I write a lot of “core” code in Java, as I prefer the verbosity of it somehow, but then I find myself a lot of times I just need a lot of utilities or “quickies” around this code — be it for unit testing purposes or to provide nicer interfaces to the outside. And that’s when I switch to Groovy language and its syntactic sugar so to speak.
I write about 50% of my unit tests in Groovy nowadays — though, granted, partially because of the Spock framework too. Also, I tend to write most of my beans now using Groovy too as it allows for a more terse syntax while achieving the same. I’ll walk you in this post through one of the niceties in Groovy around Java beans.
First of all, I’ll just say, that before using Groovy for my Java beans, I did try out the Project Lombok in Java and relied on its annotations for generating getters, setters, constructors and so on. However, I found that at time to be buggy and it still needed a few annotations in place for what seems to me rather a natural thing when it comes to Java beans: constructor, getters and setters. As such, I ditched it in the end — and I’m sure the framework will improve in time so soon I might have to revisit them and see where they got — and switched to Groovy.
And here’s why: it’s very easy to get all the getters and setters in Groovy just by simply declaring my property — no annotations, no configuration, just simply write (as I’m sure you know):
class MyBean { def someProperty def someOtherProperty } |
And right away I get get/setSomeProperty
and get/setSomeOtherProperty
out of the box!
Now this is nothing new to anyone who at least heard of the Groovy language. And since Groovy has the nice feature of multiple assignments, then I can rely on a default constructor and set these 2 properties in one go:
def x = new MyBean() x.with { (someProperty, someOtherProperty) = [value1, value2] } |
However, what if I want to do it all in one line?
def x = new MyBean(valueForSomeProperty, valueForSomeOtherProperty) |
At first you’d be tempted to write your own constructor, Java style:
class MyBean { def someProperty def someOtherProperty MyBean(def someProperty, def someOtherProperty) { this.someProperty = someProperty; this.someOtherProperty = someOtherProperty; } } |
Luckily though, there’s no need for that: Groovy have a (nice!) annotation: @TupleConstructor — annotate your class with it and the constructor comes out of the box:
@TupleConstructor class MyBean { def someProperty def someOtherProperty } |
Now you can just write in one line:
def x = new MyBean(valueForSomeProperty, valueForSomeOtherProperty) |
Without all the boilerplate code Java requires. Neat, huh? 😉