Unadulterated Java is so groovy
Groovy is an alternate language for the JVM– alternate in that Groovy is a simpler, more expressive Java (which, by the way, also happens to work with normal Java). In fact, if you already know Java, you basically know Groovy, man.

Groovy’s syntax is a less strict version of Java’s and adds a few new features here and there. You could say that Groovy’s syntax is terse, which yeilds a highly expressive medium for conveying behavior without a lot of extranous verbiage. But the beauty is that that verbiage isn’t gone– it’s assumed. Hence, Groovy is an unadulterated version of Java, baby.
As a demonstration, here is a hip Java class that represents a song, aptly named Song. As you can imagine, this code exists in a file named Song.java and is located in some sort of package structure (like com.acme.blah).
public class Song {
private String name;
private String genre;
private String artist;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getGenre() {
if(genre != null){
return genre.toUpperCase();
}else{
return null;
}
}
public void setGenre(String genre) {
this.genre = genre;
}
public String getArtist() {
return artist;
}
public void setArtist(String artist) {
this.artist = artist;
}
}
This bogue class doesn’t do anything particularly interesting and is basically a JavaBean– but it serves as an excellent demonstration of how you can achieve the same behavior (albeit simple) in Groovy with fewer lines of code.
As a first step, you can make this a Groovy class by just changing the file’s type to .groovy– in fact, Song.groovy as is, will compile just fine with groovyc.
One thing about Groovy is that it is Java without accessibility modifiers (i.e. you don’t have to specify public– everything is assumed to be so unless you say otherwise) and semi-colons. Consequently, I can trim down this class somewhat by removing all semi-colons and public modifiers, baby.
class Song {
private String name
private String genre
private String artist
String getName() {
return name
}
void setName(String name) {
this.name = name
}
String getGenre() {
if(genre != null){
return genre.toUpperCase()
}else{
return null
}
}
void setGenre(String genre) {
this.genre = genre
}
String getArtist() {
return artist
}
void setArtist(String artist) {
this.artist = artist
}
}
Already, because it’s my bag, Song is getting a bit shorter, but nothing to write home about.
What’s particularly handy in Groovy is the way it treats properties– in this case, Song has 3 (name, genre, and artist). By convention, in Java, if you want to access these values (i.e. via getters and setters) you copasetically create corresponding setProperty and getProperty methods. In Groovy, these accessors are generated for you; consequently, in the Song class, I can remove those methods leaving me with the following code:
class Song {
private String name
private String genre
private String artist
String getGenre() {
if(genre != null){
return genre.toUpperCase()
}else{
return null
}
}
}
Note that I left in the getGenre method– that’s doing something special.
Be careful though, disco dancers, as in Groovy, if I leave the properties as private Groovy will not generate the accessors– accordingly, the next step is to remove the private modifier on the properties.
class Song {
String name
String genre
String artist
String getGenre() {
if(genre != null){
return genre.toUpperCase()
}else{
return null
}
}
}
Looking at this code, I can hear the Java faithful grinding their teeth over what appears to be a lack of encapsulation, baby– in fact, in Groovy, you can access the name property directly!
Or do you?
Using a simple GroovyTestCase, I can knock out a quick test to see property access in action:
class SongTest extends GroovyTestCase {
void testPropertyAccess() {
def sng = new Song(artist:"Lipps, Inc",
name:"FunkyTown", genre:"Disco")
assertEquals("FunkyTown", sng.name)
assertEquals("FunkyTown", sng.getName())
}
}
In the code above, I’m grabbing a property either directly or via the getter method– the same, by the way, is true for setting a value. But the question remains, when the property is seemingly accessed directly, does this by pass the getter (or setter)?
One way to find out is to use the getGenre method, right? It does something special– accordingly, the following test case demonstrates hip encapsulation in action:
void testEncapsulatedAccess() {
def sng = new Song(artist:"Lipps, Inc",
name:"FunkyTown", genre:"Disco")
assertEquals("DISCO", sng.genre)
assertEquals("DISCO", sng.getGenre())
}
Even though the properties in the Song class are not explicitly private, they are acting privately, aren’t they, man?
Going back to the getGenre method on the Song class, it turns out that Groovy also has a handy syntax for null pointer safety, consequently, I can simply that method even further.
class Song {
String name
String genre
String artist
String getGenre() {
return genre?.toUpperCase()
}
}
Groovy also permits dropping return statements– in essence, the last line of a method is assumed as the return value. So, that leaves the getGenre method as:
String getGenre() {
genre?.toUpperCase()
}
Groovy infers types– for instance, writing String value = "groovy"; is a bit verbose, no? Think about it for a second– String value is superfluous isn’t it? value must be a String as I set it to one, right? Likewise, in Groovy, value is clearly a String (because it is set to a String directly!) without having to give the compiler (or runtime) a hint. Accordingly, you can drop types and replace them with Groovy’s hip def keyword.
class Song {
def name
def genre
def artist
def getGenre() {
genre?.toUpperCase()
}
}
Removing an explicit type does have some consequences though– in this case, given that Groovy is Java, these properties must have some type associated with them. What do you think that type is? Right! java.lang.Object, baby. Consequently, if you were to use this Groovy Song class in Java, the getGenre method will have a return type of Object, not String (unless you explicitly make String the return type).
Applying groovy techniques to Java yields a more effective Java– in this case, the Song class started out at roughly 30 lines of code. Refactoring it down a bit by leveraging Groovy, I ended up with basically 10 lines of code. The code is essentially the same– the only behavioral difference being that Object is now king with method return types (should you use this class in normal Java). But switching out def for String doesn’t add any new lines of code, does it?
Groovy is unadulterated Java– in fact, it’s Java without a lot of Java. Can you dig it, baby?
Friday 07 Mar 2008 | Andy | Groovy
Wicked! we want more content like this!
[…] Original post by Andy […]
Andy is such a humble cat that he has yet to post anything about his big news. This week, the book he co-authored, Continuous Integration, won the Jolt Award for best technical book. That’s like so way better than 8-track! Congrats, Andy. You’re grooving!
Many thanks, Andrew– it was a pleasure to see you at SD West!
It seems like atleast once a week I hear about a new dynamic language that’s going to make me work faster, get more done, and save us from the communist. Its at the point that I ignore most of them.
I did the same with Groovy, until now. This was great summary. It reminds me of how everyone jumped on C++ at first because it was backwards compatible with C.
In this example, the Java code has more lines i agree, but it describes more properties for the class, than the groovy example.
For example, the private modifier in “genre” prohibits a developer that just uses the class to accidentally reference the content without using the getGenre … right?
In the groovy counterpart i could just say Song().genre … right? (i’m not a groovy expert though).
In addition, i think the example is not very indicative … since it is easy to ommit and simplify things things in a getter/setter class.
My experience with dynamic languages (especially python and Perl) is that they have earned their place, but they cannot be used efficiently in large applications.
Vassilios, even with the simplified syntax Groovy does generate getters/setters for each property (in byte code) which means that a call like Song().genre is in fact Song().getGenre() It looks like direct field access but it isn’t, it is still property access.
To be honest i would excpect the opposite :). Why bother generate the getGenre() method in bytecode if the end programmer will always use the property?
In Java also, noone is forcing anyone to write getters/settters. You can forget about them if you like
And believe me, except the genre? the code will look exactly the same
public class Song {
public String name
public String genre
public String artist
public String getGenre() {
if(genre != null) { return gerne; }
return “”; // something …
}
My previous comment suggested that you dont have strict OO concept in those languages (talking mostly from my python experience though).
It’s fast and beautiful, i agree. But it has its limitations :). Serves its puprose though.
I dont think that are really comparable though
The article covers using the Groovy written class in Java, to have a terser syntax. So in that sense they are directly comparable because the Groovy code is pretty much exactly equivalent to the Java code at the byte code level that only difference being the Groovy one will implement the GroovyObject interface.
In terms of the setters and getters they are however directly equivalent. And regardless as to whether people are forced to write getters/setters. Sun pretty much dictated this decision with the release of the JavaBean spec donkies years ago.