Why and When to use Groovy

I have just started learning Groovy few days back.The first thing that I have asked myself and searched for is 'Why should i use groovy over java and When I can use Groovy. ?'

I am following the book 'Programming Groovy'. The things I have understood regarding 'Why' part are

Simplicity : Groovy syntax is simple and easy. It saves a lot of code and effort thus increasing the productivity of developer if he had to do the same thing in Java.

in Java

for(int i = 0; i < 3; i++) { System.out.println("United United..." ) }

in Groovy

3.times {
println "United United..."
}

This is just a trivial example but there are lot more things like this.

Groovy's Dynamicity : This is one reason why coding is made simpler and concepts like polymorphism and
callback patterns are made easy to implement.

class Player {
String name
int age
}
class Club {
String name
String city
}
public printNameOfTheFootballingEntity(entity) {
println "the entity with name "+ entity.name + " is related to Football"
}

player = new Player(name:"Giggs", age:35)
club = new Club(name:"ManchesterUnited", city:"Old Trafford")
printNameOfTheFootballingEntity(player)
printNameOfTheFootballingEntity(club)

Consider above code. It prints the following:

the entity with name Giggs is related to Football
the entity with name ManchesterUnited is related to Football

If you observe there is no compile time check for the presence of the property "name" in the entity. While interpreting Groovy checks for this property and if it is not there it throws the Missing Property Exception. Dynamic!! ain't it?

In Groovy you dont need to end statement with semicolon.

Closures are the piece of code blocks contains some statements. They are like fucntion pointers in C. They are infact objects in groovy and can be passed to functions as arguemts as well. Closures can do the job of callbacks.

For Example

def checkPlayer = {
println it + " is a good Striker"
}

list = ["Rooney", "Tevez" , "Berbatov" ]
list.each(checkPlayer)

The above code prints the following

Rooney is a good Striker
Tevez is a good Striker
Berbatov is a good Striker

Here 'it' represents the each single item in the list that is passed to the Closure 'checkPlayer'.

The code inside the braces is closure code acting like a callback for all the elements of the set.

The same thing in Java will be a bit more effort to code.

List list = new ArrayList();
list.add("Rooney");
list.add("Tevez");
list.add("Berbatov");

for (String player : list) {
checkPlayer(player);
}
private void checkPlayer(String player) {
System.out.println(player + "is a good Striker");
}

The examples so far shows the ease with which things can be developed with little effort but ultimately have the same result because the groovy code is compiled to bytecode which JVM understands. This can make a developer more productive and it can give more agility.

Groovy accepts almost all Java programs as it can use the Java libraries and it even extends some core Java classes as well.

For example

list.join()

This prints 'RooneyTevezBerbatov'. Groovy has added the join() method on the 'List' of Java while retaining remaining methods.

All is well. These are some reasons which are good enough for any Java developer to explore Groovy.

Now the big Question arises 'When can I use Groovy over Java?' and 'What sort of applications are targeted?

I am at the moment stuck at this question. Honestly speaking i didn't get a sufficient answer . I think this 'When' question is really important especially if some thing is improved over some other thing and you are comparing both.

Groovy scripts are interpreted at runtime, this might cause some performance overhead, which is not all that bad. You can always compile it to java bytecode to remove that performance penalty.
Other reasons may be revealed to myself after some more exposure, about what kind of applications can be created using Groovy. I will share it my next blog. But any suggestions and thoughts are always welcome!

References:
'Programming Groovy' Book

Comments (21)

  1. Erik Pragt - Reply

    January 2, 2009 at 10:49 am

    Nice blog Sunil, though personally I think the question should be: why choose Java over Groovy?

    Btw, Groovy scripts are not interpreted at runtime. They are compiled at runtime, and the bytecode is run, not the script itself. The performance overhead you get is not because of this, but because of the invocations in Groovy: everything is done through reflectionm, be it calling a method or accessing properties.

    Also, in a 'normal' application, you would use a join compiler, which would compile the Groovy code into bytecode, therfore removing the 'at runtime' compilation.

    Try to write a normal Java application (EJB, Web frontend, etc) in Groovy. I think it will answer your question. I haven't found a good reason not to use Groovy in my Java applications (and speed is, in our applications, usually totally irrelevant on a language level)

  2. Stephan Schmidt - Reply

    January 2, 2009 at 10:52 am

    Basically you're right. Just to nitpick 🙂

    System.out.println("United United..." )

    can be written as just

    println("United United..." )

    In Java (Static imports).

    And

    List list = new ArrayList();
    list.add("Rooney");
    list.add("Tevez");
    list.add("Berbatov");

    can be written as

    List list = List("Rooney", "Tevez", "Berbatov")

    the static List method is trivial to write with varargs...

    (or see Google collections for an implemntation)

    Peace
    -stephan

    --
    Programming is hard - http://blog.codemonkeyism.com
    http://twitter.com/codemonkeyism

  3. Maarten Winkels - Reply

    January 2, 2009 at 11:19 am

    Nice one, Sunil! Your blog show some very useful features of Groovy with simple examples.

    Good question: 'When should you use Groovy'. Feature wise there is no reason not to use Groovy: Java with all its features is used under the hood and it seems like we're only adding new features without loosing any, so why not just always use Groovy, as Erik suggests?

    I think there are many other factors that make a development environment successful apart from the language used: availability of programmers, infrastructure tooling (build tools, code analysis tools, editors), support from vendors and consultants, etc.

    At this point, I don't know much about how large projects are run that use Groovy, although I have seen that big shops that use Java usually spend a lot of time getting the development environment right. I would guess that to get a working development environment for Groovy, you can build upon the existing tooling for Java (just as the language itself). Maybe somebody with more experience in doing Groovy projects can comment on the when and how question.

  4. Sunil Prakash Inteti - Reply

    January 2, 2009 at 11:42 am

    Erik, Thanks for the correction regarding the runtime compilation and your insight on reflection mechanism in groovy.

    Maarten,Thanks for your comment on 'When' part.

    Based on these comments i now get the feeling that there is no reason not use groovy

  5. Markus Jais - Reply

    January 2, 2009 at 2:49 pm

    I agree with Eric. I think many Java applications that are currently written can also be written with Groovy. And with the great support in Netbeans 6.5, it's a real joy.
    Groovy code is shorter. And often shorter code is easier to read. Some people find Groovy (or Ruby) less readable than Java, but this is mostly because they have been using Java for 10 years and Groovy for 4 weeks.
    If you are proficient in both languages, you will find the shorter Groovy code easier to read most of the time.

  6. James Hughes - Reply

    January 2, 2009 at 3:13 pm

    One of the big concerns with Groovy is, especially comapred to Java, a distinct lack of tooling. The plugins for Eclipse, NetBeans etc are Passable but certainly not up to the standards of the established Java equivalents. In a big project this is certainly a problem. Escpecially when you need to consider developers experience. Personally I am fine with TextPad but some of my collegues would be lost wihtout the helping hand of eclipse.

    James.

  7. Bob Herrmann - Reply

    January 2, 2009 at 4:21 pm

    Or more simply, "When considering Java or Groovy, choose Groovy."

  8. Lincoln - Reply

    January 2, 2009 at 7:17 pm

    Remember, you don't need to use "text" + var + "text" to concatenate strings! You can Perl/PHP like variable interpolation such as "text $var text" !!! I'm glad Dynamic programming has come to the JVM. Lots of benefit without the loss of performance!

  9. rod - Reply

    January 2, 2009 at 8:12 pm

    My feeling is that Groovy cannot replace java. There are many situations where duck typing is not so good. But since Groovy is Java, you can type your objects inside a Groovy program. So finally, your aplication becomes a mix of Java and Groovy. But the question of when to use Groovy or not remains unclear (at least to me). Performance is probably an important driver. Tooling (mainly the IDE) is another one; think of refactoring functions provided by IDEs for Java programs: some of them can simply not be implemented for Groovy just because of its "dynamic" nature.

  10. Alain - Reply

    January 3, 2009 at 2:59 am

    Hi,

    Here there is my experience about when use Groovy. It is possible to embed a groovy console into a java application so you can control your application with groovy scripts you type into the console.
    You can into the console fire e method of your java application. It can be useful in development stage to make some tests.
    I don't know if I'm very clear. To sum up in your java code you can launch a console and have access to the parameters and you can call functions.

  11. Jan-Kees van Andel - Reply

    January 3, 2009 at 4:54 pm

    It might be useful to note that as part of Java 7, the JVM will have MUCH better support for dynamic languages like Groovy.
    Think of features like tail calling, invokedynamic and interface injection.
    Those features are part of JSR 292.

    See http://blogs.sun.com/jrose/entry/interface_injection_in_the_vm for an interface injection article,
    http://blogs.sun.com/jrose/entry/tail_calls_in_the_vm for a tail calling article and
    http://blogs.sun.com/jrose/entry/dynamic_invocation_in_the_vm for invokedynamic.

    Also, Alex Buckley and Brian Goetz did a talk on the subject at DeVoxx 2008. The slides will be published on Parleys.com somewhere in 2009.

  12. Alain - Reply

    January 3, 2009 at 8:16 pm

    just to complete my precedent post. when I say you can control your java class with the groovy console it's while your application is running. it's like with JConsole where you can control your JMX Beans. But with Groovy it's more powerful.

  13. robert zaleski - Reply

    January 4, 2009 at 5:35 am

    To me dynamic/scripting languages break down in projects of a large size. I think of it being like writting C with tons of pointers. There is a lot of power (with dynamically adding methods and variables) but this is the very thing that makes it hard to scale well. You get easier testing, but you HAVE to test everywhere, if nothing else to make sure your spelling is correct. I've worked on two large systems in PERL and JavaScript and both have gotten unruly when they hit a certain size.

    For quick or very isolated chunks, I love dynamic languages, especially Perl. But for anything that may grow into something large I would hesitate.

    Just my two cents.

  14. x1311 - Reply

    January 4, 2009 at 4:23 pm

    Hi there,
    I often thought about the same question, too. First of all I am not the biggest fan of all those dynamic languages as I prefer static typing. For me personal, it is very important when I read code to allways know what the type of an particular object is. Others will say "Hey, Dynamic languages are easliy readable by any human". That´s true. But when it comes to more technical details this doesn´t help you anymore. You have to dive into a debug session .. I think groovy as an dynamic language is perfect for building very isolated and autarc components where only one developer makes it all. But I could not imagine a big team building an enterprise project explicitly using groovy. This could work if you have a big catalogue of coding and naming conventions to give some guidelines. But I doubt that really works in reality.
    I think this is not a groovy problem but a problem of nearly all dynamic languages.

    My 2 cents ..

  15. Josh Brown - Reply

    January 4, 2009 at 11:48 pm

    One thing I really like about Groovy is that it removes the need for String concatenation, so in your above example, you could've done this:

    def checkPlayer = {
    println "$it is a good Striker"
    }

    To put a variable's value in a String, just use the dollar sign syntax as shown above. You can also use it when calling methods on objects, like so:

    public printNameOfTheFootballingEntity(entity) {
    println "the entity with name ${entity.name} is related to Football"
    }

    No plus signs necessary!

  16. ken - Reply

    January 31, 2011 at 7:28 pm

    Language will last only if it is of any practical use. The question you asked is really valid but answers are not. Those can't be the reason for using Groovy. Someone (from Groovy community) has to give few practical usage (with good documentation) then only people will start using it for commercial purpose (not only as hobby). Once that process is triggered, automatically new people will start giving more creative inputs, igniting the whole process.

    Right now, I only have opinion that Groovy can be lot more helpful (whether it can replace Java or not is not at all important) but how I don't know. I'm starting some research on using "Groovy with Window", will let you know the result if it turn out to be practical solution [more detail - want to execute vb macros through Groovy( or java) as no proper solution for excel in java is available. POI disappointed us!!!].

  17. ken - Reply

    January 31, 2011 at 7:38 pm

    Jan-Kees van Andel, thanks for those links (Java 7).

  18. Sandeep Sangole - Reply

    September 5, 2011 at 5:59 am

    I am using groovy in my project.But I dont see much benefit except its dynamic and saves few lines of code. I think if groovy helps more on performance ,then it would be good idea to go for groovy.

  19. Denisha Stjohns - Reply

    June 23, 2012 at 8:41 pm

    I was just looking for this information for a while. After 6 hours of continuous Googleing, finally I got it in your website. I wonder what's the lack of Google strategy that don't rank this kind of informative websites in top of the list. Normally the top websites are full of garbage.

  20. Elangovan ARUMUGAM - Reply

    August 22, 2012 at 2:52 pm

    Thanks a lot Erik Pragt, Maarten Winkels and Markus Jais

    Got very good clarification about Groovy's Compilation and Run the script.

    And many thanks to Sunil Prakash Inteti posted this blog.

    As discussed by Markus Jais, Now only we are started to work on Groovy, so we feel Java is providing a better readability.

    I am new to Groovy-2.1. Started to develop groovy applications thro Eclipse 4.2 (Juno)

    Development Builds
    Eclipse level : 4.2 (Juno)

    Development update site: http://dist.codehaus.org/groovy/distributions/greclipse/snapshot/e4.2/

    Please read this to do groovy setup:
    STEPS:
    A. Environment Setup
    1. Download JDK-1.6 (jdk1.6.0_23) and Install in the following location
    C:\Program Files\Java\jdk1.6.0_23

    2. Download Tomcat 6.0 (apache-tomcat-6.0.24)
    Unzip it in the following location
    C:\Program Files\apache-tomcat-6.0.24

    3. Download Eclipse 4.2 (eclipse-jee-juno-RC3-win32 - Juno)
    go to Help menu -> Install New Software -> Click Add button
    Name: Groovy Dev Plugins
    Location: http://dist.springsource.org/release/GRECLIPSE/e4.2/

    4. Download MySQL 5.5 Server and install it at C:\Program Files\MySQL\

    5. Set Environment variables
    Select Computer icon-> properties -> Advanced system settings -> Environemnt Variables

    User variables ->
    a.
    Variable name : JAVA_HOME
    Variable value : C:\Program Files\Java\jdk1.6.0_23

    b.
    Variable name : TOMCAT_HOME
    Variable value : C:\apache-tomcat-6.0.24

    c.
    Variable name : GROOVY_HOME
    Variable value : C:\groovy-binary-2.0.1\groovy-2.0.1

    d.
    Variable name : GRAILS_HOME
    Variable value : C:\grails-2.1.0\grails-2.1.0

    System variables ->
    Edit Path

    Variable name : Path
    Variable value : ;%JAVA_HOME%/bin;%TOMCAT_HOME%/bin;%GROOVY_HOME%/bin;%GRAILS_HOME%/bin;

    6. Create a workpace folder in the following location
    C:\groovy_on_grails_workspace

    Copy CoEGroovy folder from Project to groovy_on_grails_workspace

    Then open Eclipse-4.2 Juno IDE,
    It will ask to open this IDE in a workspace, please refer "C:\groovy_on_grails_workspace"

    7. Load Existing Project from Workspace
    File -> Import -> General -> Existing Projects into Workspace click Next
    Select root directory: click on Browse button, which should be points in to C:\groovy_on_grails_workspace\CoEGroovy

    Then click Finish

    8. To avoild compilation issue
    Select CoEGroovy Project -> right click -> Properties -> Java Build Path -> click on Add JARs...
    CoEGroovy -> lib
    add releavant jars, Then click Ok, Ok ...

  21. Polyk - Reply

    August 13, 2015 at 9:12 am

    Groovy makes the code very simple and helps quick development. But for an enterprise application I will not use it because you'll discover many conding errors at runtime while you can early see them with Java. When you use a wrong field in your code, there is an impact from front to back-end and companies will not accept that.
    - Quick but not safe as Java
    - Refactoring huge applications is easier with Java.....how can you do that with Groovy ?
    - Groovy is nice but not robut in my opinion
    For me Groovy is a nice to have

Add a Comment