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

'http://nerdysermons.blogspot.in'.toUrl().text

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]){
    panel(){
        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.



19 comments:

Unknown said...

Those guidelines additionally worked to become a good way to
recognize that other people online have the identical fervor like mine
to grasp great deal more around this condition.


java training in chennai


java training in bangalore

ciitnoida said...

Ciitnoida provides Core and java training institute in

noida
. We have a team of experienced Java professionals who help our students learn Java with the help of Live Base Projects. The object-

oriented, java training in noida , class-based build

of Java has made it one of most popular programming languages and the demand of professionals with certification in Advance Java training is at an

all-time high not just in India but foreign countries too.

By helping our students understand the fundamentals and Advance concepts of Java, we prepare them for a successful programming career. With over 13

years of sound experience, we have successfully trained hundreds of students in Noida and have been able to turn ourselves into an institute for best

Java training in Noida.

java training institute in noida
java training in noida

Radha Karthi said...

Fantastic blog!! with loads and loads of latest info.Thanks for sharing.

Selenium Training in Chennai
Best Selenium Training Institute in Chennai
ios developer training in chennai
.Net coaching centre in chennai
French Classes in Chennai
Big Data Training in Chennai
Best JAVA Training in Chennai
Java training institutes in chennai
java certification course in chennai
java certification training in chennai

Anonymous said...

The knowledge of technology you have been sharing thorough this post is very much helpful to develop new idea. here by i also want to share this.

Big Data Hadoop Training In Chennai | Big Data Hadoop Training In anna nagar | Big Data Hadoop Training In omr | Big Data Hadoop Training In porur | Big Data Hadoop Training In tambaram | Big Data Hadoop Training In velachery




praveen said...

Thanks for sharing such informative guide on .Net technology. This post gives me detailed information about the .net technology. I am working as trainer in leading IT training academy offering Dot Net Training in Chennai and i use your guide to educate my students.




Dot Net Training in Chennai | Dot Net Training in anna nagar | Dot Net Training in omr | Dot Net Training in porur | Dot Net Training in tambaram | Dot Net Training in velachery

Jayalakshmi said...

Thank you for sharing such great information with us. I really appreciate everything that you’ve done here and am glad to know that you really care about the world that we live in..
data science training in chennai

data science training in tambaram

android training in chennai

android training in tambaram

devops training in chennai

devops training in tambaram

artificial intelligence training in chennai

artificial intelligence training in tambaram

deiva said...

Thank you for sharing such great information with us. I really appreciate everything that you’ve done here and am glad to know that you really care about the world that we live in..
java training in chennai

java training in omr

aws training in chennai

aws training in omr

python training in chennai

python training in omr

selenium training in chennai

selenium training in omr

Anonymous said...

perde modelleri
sms onay
Vodafone Mobil Ödeme Bozdurma
nft nasıl alınır
ankara evden eve nakliyat
trafik sigortasi
dedektör
web sitesi kurma
AŞK KİTAPLARI

Samia Beel said...

Microsoft Office Suite 2007 Service Pack 3 1.0 for Windows. Fast downloads of the latest free software! Click now.. MS Office 2007 Crack Download

The Blogger Worlds2 said...

Free download HandBrake 1.5.1 full version standalone offline installer for Windows PC,. HandBrake Overview. HandBrake is an effective and highly Handbrake Free Download

betturkey said...

Success Write content success. Thanks.
betmatik
kıbrıs bahis siteleri
deneme bonusu
canlı slot siteleri
betpark
kralbet
canlı poker siteleri

korsan taksi said...

Good content. You write beautiful things.
sportsbet
taksi
hacklink
mrbahis
hacklink
vbet
vbet
sportsbet
mrbahis

hakan said...

sms onay
PAV

aslı said...

kocaeli
konya
kuşadası
kütahya
malatya
Y2T

cansu said...

erzurum
kuşadası
ümraniye
beşiktaş
ataşehir
L2NO

rıdvan said...

başakşehir
beykoz
gölcük
kütahya
bandırma

İRY

irem said...

ağrı
muş
mersin
afyon
uşak

MLKG

yavuz said...

ağrı
aksaray
amasya
antep
ardahan
KNZ4FZ

Anonymous said...

افضل دهانات في ليبيا

Post a Comment