Ten Reasons Every Java Developer Should Learn Groovy (Part 1)
This is part one of my two part post on some of the many reasons that a modern Java developer really should take an hour and learn Groovy. It really is the age of the polyglot programmer, and there are a ton of new and interesting languages on the JVM. Of all those JVM languages I dare to say Groovy is the closest tied to Java, so it offers a ton of advantages with a more gentle learning curve for a Java developer than some other JVM languages.
10) Sometimes you need a scripting language.
The fact is there are many times on any project where a solid scripting language comes in handy. Whether you need to automate some pesky task, quickly process some data, or just test out an idea, Groovy is an ideal choice for the busy Java developer. Groovy allows you to get rid of a lot of the formaility you would need and just concentrate on a quick solution to the problem at hand. Here is a quick example of Hello World.
In Java…
public class MyClass {
public static void main(String args[]) {
System.out.println("Hello World");
}
}
That was a lot of work to print 'Hello World', what does the same code look like in Groovy?
println 'Hello World'
That's it, all there is to it. So looking at the Java version its about three lines of code with a couple extra with braces. What can we do in Groovy in three lines?
import groovy.sql.Sql
sql = Sql.newInstance( 'jdbc:jtds:sqlserver://serverName/dbName-CLASS;domain=domainName',
'username', 'password', 'net.sourceforge.jtds.jdbc.Driver' )
sql.eachRow( 'select * from helloTable' ) { println "$it.id -- ${it.hello}" }
So in the same number of lines of code I can actually query my Hello World from a database using Groovy. Groovy offers a concise and powerful scripting solution, that still works with all your Java code, Maven dependencies, etc.
Another awesome benefit of installing Groovy is the groovyconsole, the groovyconsole allows you to quickly execute bits of code interactively.

Learn more… * Groovy for Beginners * Groovy in Action * Grapes and Grab - import Maven dependencies into Groovy scripts
9) Seamless Integration with Java
If you're a Java programmer and work at a Java shop the odds are you have a ton of Java code being used, well you don't want to have to throw all that out just to get some productivity gains from a new language. With Groovy you don't have to. It is extremely compatible with Java, and the Java tooling, JUnit, Maven, Spring, Apache Commons, etc. all work wonderfully with Groovy, in fact Groovy classes compile into Java bytecode and run natively on the JVM so its seemless to call Groovy from Java and vice-versa.
One example I like a lot is Groovy beans. We're all familiar with Java beans, classes that have a bunch of variables in the first quarter of the file then the rest of the class is filled with boilerplate, autogenerated setters and getters, well with Groovy you can avoid all that extra code with Groovy Properties.
Here is a quick example:
class TvShow {
String name
String network
List<String> cast
int episodeCount
}
There are a couple of things to point out about the above class, the first is that we don't start with public class, how often do you make your classes anything other than public? In Groovy public is the default for classes. The next thing to note is that I didn't specify access modifiers before my variable declarations, in Java this would make them package-private, the question is, when is the last time you actually used package-private? In Groovy they eliminated package-private and instead all instance varilbes without an access modifier are now 'Properties', properties get autogenrated setters and getters, and the nice thing is this happens at compile time, so from my Java code I can call 'tvShow.setName("Arrested Development");', but with less than half the lines of code.
Learn More * Groovy Beans
8) GDK
Groovy is all about being a better Java experience, so in Groovy they didn't redefine any of the core JDK classes we all know an use. What they did is create the GDK, which is a set of extensions of the base JDK classes that make programming in Groovy much more enjoyable.
For example:
There are a bunch of useful methods added to java.net.URL that allow you to painlesly pull data from URLs.
//Get the text of a page a URL points to
String content = new URL('http://google.com').getText()
//Read a remote resource byte by byte
new URL('http://www.google.com/intl/en_com/images/srpr/logo3w.png').eachByte { byte -> //process data }
Or you can format a date with out creating a SimpleDateFormatter
new Date().format('MM/dd/yy')
And if you combine the fact that for all intents and purposes Groovy has done away with Java primitives and just uses Integer, Double, etc. with the GDK versions of those classes you can do cool things like:
5.3423d.round(2) // result is 5.34
5.downto(0) {n -> println "${n}"} // prints the number 5 to the number 0
A lot of these are fairly contrived examples but hopefully they illustrate the point, that Groovy adds a lot of powerful features to the JDK that can save a ton of time and energy.
Learn More
7) Builders
The Groovy language has baked in support for the builder pattern, builders make it insanely easy to generate things like XML, HTML, Ant tasks, Swing UIs, and a ton more. Here is a quick example of how you can use Markup Builder to build out some HTML.
import groovy.xml.MarkupBuilder
def writer = new StringWriter()
def xml = new MarkupBuilder(writer)
def bodyParagraphs = ['paragraph 1', 'paragraph 2', 'paragraph 3']
xml.html() {
head() {
link(href:'css/style.css', type:'text/css', rel:'stylesheet')
}
body() {
div(id:'mainContent') {
h1('My Awesome Page')
bodyParagraphs.each { p(it) }
}
div(id:'footer') {
p() {
a('Contact Us', [href:'mailto:support@something.com'])
}
}
}
}
println writer
This code will output:
<html>
<head>
<link href='css/style.css' type='text/css' rel='stylesheet' />
</head>
<body>
<div id='mainContent'>
<h1>My Awesome Page</h1>
<p>paragraph 1</p>
<p>paragraph 2</p>
<p>paragraph 3</p>
</div>
<div id='footer'>
<p>
<a href='mailto:support@something.com'>Contact Us</a>
</p>
</div>
</body>
</html>
As you can see it makes programatically generating things like XML or HTML markup trivialy easy. But, of course, there's more. Groovy provides a class BuilderSupport that you can extend in order to create your own builders.
Learn More
6) XmlParser and XmlSlurper
Java tends to love XML, so even though I tend to hate XML I end up working with it quite a bit. The good news is that Groovy makes XML processing much less painful.
If you follow this link you will get an XML document with the weather information for Denver, CO. So with Groovy all I have to do to start playing with that XML feed is
def xmlDoc = new URL('http://weather.yahooapis.com/forecastrss?w=12792941&u=f').getText()
def p = new XmlParser().parseText(xmlDoc)
println 'Current temperature: ' + p.depthFirst().grep{ it.@temp }[0].@temp
println 'Currnet wind chill: ' + p.channel.'yweather:wind'[0].@chill
p.'**'.'yweather:forecast'.each {
println "${it.@day}, ${it.@date} it will be ${it.@text}, with a high of ${it.@high}"
}
This is just a very basic example of the power of Groovy XMLParser, they call these expressions GPaths becuase they are close to XPaths except they are all Groovy code, so you can use closures, call methods, and paths XML nodes around in variables. Note: I listed XmlParser and XmlSlurper, they are two differnet classes in Groovy with somewhat different behavior and different performance characteristics, you can read more about their differences here.
Learn More