Ubuntu insights, Programming in groovy, java, et als!

Monday, April 23, 2012

Why Groovy over java?

Some reasons why java developers should consider adapting groovy.

Groovy is married to java 

Groovy's seamless integration with java makes it possible to use all frameworks and libraries available for java, without any hassles regarding language compatibility. Groovy is so much compatible with java that one can merely change the .java extension to .groovy and run it. After all, groovy is just dynamic java with some add-ons and wrappers.

Dynamic typing

Unlike java, groovy does not throw compilation errors on your face. One of the biggest pleasure when compared to java, groovy doesn't impose explicit type casting which is a pain in the butt while programming in java. Groovy is a programmer friendly language and doesn't go out of control as long as the programmer is sure about his own code. It also supports optional typing, the native java syntax can be retained. 

Blocks and closures 

One of the best aspects of groovy is that it provides higher level constructs like blocks and closures found in languages like Smalltalk and Ruby. Block closures are handy powerful features which java lacks.

//To extract the first letter out of each element of a list.
def words = ['animal', 'bird' , 'cat', 'fly', 'dog']
def letters = words.collect{ it[0] }
println letters

//easy iterations
words.eachWithIndex{ word, index ->
    println "$word at $index"

The list goes on. Further refer : find{}, findAll{}, sort{}, each{}, contains{} et als, all of which make programming a breeze. 

Reflection in hand

As in smalltalk, Groovy has a concept of metaclass while initializing objects. This metaClass provides wrappers around the native Reflection API of java which enable the programmer to change the behavior of a class at run time.

For example : When compared to java, inspecting the methods of a class at runtime is as simple as :

class Test{
def one = 1
    def getOne(){
        return one

println Test.metaClass.methods //prints getOne() and all methods default methods of the class.

Likewise to inspect the properties of a class at runtime, 

println Test.metaClass.properties //prints one and other properties if any

Likewise, injecting a method called getTwo() is as simple as :

Test.metaClass.getTwo = { return 2 }

Sugar Syntax

Besides addition of new language constructs, Perhaps this is one other aspect of groovy which hugely differentiates it with java.

Here I display two good examples that would make groovy an obvious win w.r.t to its sugar syntax.

ex: 1) A program to fetch the contents of a file in java would add up to around 10 - 15 lines. In groovy :

new File('C:\Temp\input.txt').getText()

Or further more, Parsing it is as simple as

new File('C:\Temp\input.txt').eachLine{ line ->
 //parsing logic

ex: 2) Given a url, to read the contents of a webpage, in java there is all this crap of opening streams, buffered readers and piping the contents, handling the exceptions etc. In groovy it is as simple as


Further more...

Groovy has excellent wrappers around basic java functionalities. For example: With SwingBuilder, building swing UIs becomes darn simple.

For example: To built a swing application with a click me button and text area that prints hello message upon button click, a java program for the same would extend to more around 30 - 40 lines of code with initialization, building UIs, writing an actionListener etc. In groovy, this four liner script would suffice. 

new groovy.swing.SwingBuilder().edt{
    frame(show:true, size:[200,270]){
        button(label:'Click Me', actionPerformed :{ta.setText('Hello')})
        ta = textArea(columns:20, rows : 10)

Another great feature of groovy is its ability to build, create and parse XMLs with its XmlParser and XmlSlurper facilties. Some other include inbuilt assertions, GPath expressions,    String interpolations, etc.

I can go on like this for some time. This post is an introduction to depict groovy goodness comparing it to java which is strict and verbose. The more emphasis w.r.t the groovy vs java argument is on writing less code which possesses the java-ish flavor but is a lot elegant.


Post a Comment