Our favorite Java is getting some serious competition in recent years ,
It seems there are more than 200 languages that target Java platform.
There is growing interest in languages like Scala, Groovy , Clojure , JRuby, Jython for their features and simplicity. Out of this lot we will take a close look at Groovy today as its getting wide attention in the market over recent years.
There is growing interest in languages like Scala, Groovy , Clojure , JRuby, Jython for their features and simplicity. Out of this lot we will take a close look at Groovy today as its getting wide attention in the market over recent years.
- Groovy is more or less a superset of Java
- Builds upon the strengths of Java but has additional power features inspired by languages like Python, Ruby and Smalltalk
- Could seamlessly switch back and forth between Java and Groovy
- Considered simpler and easier to learn over Jython and JRuby
- Groovy has Java-like syntax and hence the learning curve is not steep.
- Simplifies testing by supporting unit testing and mocking out-of-the-box
Once you install Groovy, you could straightaway
start programming in Groovy, just
put your Groovy jar file along with your application and get the program
working in any machine.
There are many online editors and IDE plugin available
to compile and run your Groovy code.
So what is Groovy ?
James Strachan conceived the idea of Groovy
language and started development in 2003.
Groovy is a dynamic language that dynamically
compiles the code to the Java platform. It is popular as a scripting language
and also widely used for unit testing Java code. Groovy is open source (Apache
v2 license) and is backed by VMware.
The current stable release is Groovy 2.2. You
can use Groovy in most common operating systems like Linux, Windows, and Mac.
Let’s see how Groovy looks better Java with few
examples –
Hello World Example –
// Java
class HelloWorld {
public static void main(String []args) {
System.out.println("Hello world");
}
}
// Groovy
println("hello world")
More Detailed Examples –
Let’s take a look at collection (map)
processing example. Lets create a map and do some processing in both Java and
Groovy.
// Java
Map worldCapitals = new
HashMap<>();
worldCapitals.put("England",
"London");
worldCapitals.put("Japan",
"Tokyo");
worldCapitals.put("France",
"Paris");
worldCapitals.put("Italy",
"Rome");
worldCapitals.put("USA",
"Washington");
for(Map.Entry capital :
worldCapitals.entrySet()) {
System.out.printf("%s => %s \n",
capital.getKey(), capital.getValue());
}
// Groovy
def worldCapitals = [ "England" : "London",
"Japan" : "Tokyo",
"France" : "Paris",
"Italy" : "Rome",
"USA" : "Washington" ]
worldCapitals.each {
key, value ->
println "$key = $value"
}
In this case Groovy provides a simple
array-like syntax for the Map data structure. See how use of each() method
closure makes it simple to write the code.
We all know how we write custom code to sort a
map by value in Java but the same can be achieved in a line with Groovy. See
below -
def sortedMap = worldCapitals.sort { it.value }
sortedMap.each {
key, value ->
println "$key => $value"
}
In above Groovy code, we just passed the
it.value (current iterator’s value) to the sort method. With the power of
closures, the code became much simple and readable.
Groovy provides a higher-level abstraction to
this functionality, and hence the code is much simpler.
Tip - The soon to be released Java 8 has also
introduced concept of closures in form of
"lambda expressions". It will be interesting to see how Java
is incorporating these new age language features in their new release. I will write
separate post to cover Java 8 features and capabilities soon.
XML Generation Example -
In general it’s very common to generate
structured output like HTML , XML or JSON in Java code. So let’s see one
example around this piece.
// java
PrintWriter pw = new PrintWriter(new
FileWriter("/capitals.xml"))
pw.println("");
for(Map.Entry capital :
worldCapitals.entrySet()) {
pw.printf("\t \n
\t\t '%s' \n \t \n",
capital.getKey(), capital.getValue());
}
pw.println("
");
// Groovy
def capitals =
[ "England" : "London",
"Japan" : "Tokyo",
"France" : "Paris",
"Italy" : "Rome",
"USA" : "Washington" ]
xmlbuilder = new groovy.xml.MarkupBuilder()
xmlbuilder.worldcapitals {
capitals.each {
key, value ->
country(name:key) { capital(value) }
}
}
Now just see how simple it is to do the same
thing with Groovy with lot of readability. Groovy supports builders (based on Builder
design pattern) for creating HTML and XML files.
Take away from this comparison -
- Traversing a data structure is easy in Groovy - you can use “closures” instead of plain loops and use each() method.
- Groovy is high on meta-programming and regular expression handling capabilities.
- Groovy builders are fabulous if you dealing with HTML , XML , JSON etc.
- Better for productivity and code readability for sure
- Being a dynamic language Groovy is an excellent candidate for creating DSLs (Domain Specific Languages)
We have just tried
to explore few basic features of Groovy here. You should explore further programming
improvements such as automatic check for nulls, helper methods, embedded
expressions in strings, and operator overloading. One should also explore its
meta-programming and regular expression handling capabilities.
You’ll find Grails
web framework and Groovy Server Pages (GSP) interesting if you are a serious
web-developer. If you are an admin, you may find Gradle build automation
framework useful. Grails framework (that is similar to Ruby on Rails) is built
on top of powerful and popular frameworks such as Spring and Hibernate.
Resources to learn further –
Groovy Documentation - http://groovy.codehaus.org/Documentation
Groovy Eclipse plugin -
http://groovy.codehaus.org/Eclipse+Plugin
Programming Groovy 2 - Dynamic Productivity for
the Java Developer, By Venkat Subramaniam
Groovy in Action, By Dierk Koenig,
Andrew Glover, Paul King, Guillaume Laforge, Jon Skeet
If you are a developer, tester or
script guru, you have to love Groovy. So keep grooving and have fun with it !!
No comments:
Post a Comment