InfoQ

InfoQ

News

My Bookmarks

Login or Register to enable bookmarks for unlimited time.

The content has been bookmarked!

There was an error bookmarking this content! Please retry.

Using Groovy To Write Less Code

Posted by Scott Delap on Sep 21, 2006

Sections
Development
Topics
Java ,
Scripting
Tags
Groovy
In a new IBM DeveloperWorks article, Scott Hickey compares writing code in Java versus Groovy. He finds that Groovy allows developers to focus more time writing algorithms and less time focusing on language semantics. In his first example a 60+ line JavaBean from Spring: A Developer's Notebook becomes a 24 line GroovyBean. An example focusing on testing shows how's Groovy's support for flexible constructors and setting object properties reduces code noise.  Many Java developers advocate writing unit tests in Groovy.  While organizations often have restrictions on production code, they don't have similar requirments on test cases.  The article also features examples in regards to polymorphism and Spring.

11 comments

Watch Thread Reply

Spring example by Rod Johnson Posted
Re: Spring example by Paul King Posted
Re: Spring example by Rod Johnson Posted
Good article by Rod Johnson Posted
Java 5.0 by John Davies Posted
Re: Java 5.0 by Rod Johnson Posted
very bad article by Ahmet A. Akin Posted
Re: very bad article by Ronald Miura Posted
Re: very bad article by G Giese Posted
Re: very bad article by Rod Johnson Posted
Groovy code size benefits by Paul King Posted
  1. Back to top

    Spring example

    by Rod Johnson

    The article contains an interesting example of how you can use Spring to configure and inject an object written in Groovy, with a regular bean definition.

    In Spring 2.0 there is also a value-added integration with Groovy and other dynamic languages (including JRuby) that allows you to get additional functionality, such as having the container poll the Groovy source to pick up implementation changes in a threadsafe way, while honouring references injected into callers or obtained through getBean() calls.

    An example from the Spring reference manual chapter on dynamic language support:


    <lang:groovy id="fortune"
    refresh-check-delay="3000"
    script-source="/WEB-INF/groovy/FortuneController.groovy">
    <lang:property name="fortuneService" ref="fortuneService"/>
    </lang:groovy>


    As of Spring 2.0, the Spring component model is essentially cross-language. So such components will benefit from out-of-the-box services such as declarative transaction management, and are eligible for advice by custom aspects using Spring AOP.

    Rgds
    Rod

  2. Back to top

    Good article

    by Rod Johnson

    Certainly, there are times when Groovy is very simple and concise. An interesting plus of Groovy is that it's very easy to start with for Java developers, as you can write Java-like Groovy until you become more comfortable with the additional syntax sugar and shortcuts.

    I think it's encouraging to see greater recognition of the benefits of dynamic languages on the JVM.

  3. Back to top

    Java 5.0

    by John Davies

    I'm not suggesting that Java 5 changes everything but there seems to be a lot of comparing numbers of lines and "noise". If the auther had used Java 5 features he would have seen a lot less noise not to mention lines of code from the Java versions.

    -John-

  4. Back to top

    Re: Java 5.0

    by Rod Johnson

    I'm not suggesting that Java 5 changes everything but there seems to be a lot of comparing numbers of lines and "noise". If the auther had used Java 5 features he would have seen a lot less noise not to mention lines of code from the Java versions.

    True, Java 5 is a very much better experience than 1.4 and earlier. I now find it hard to stomach having the accept all those type casts when working on older code... And simple syntax sugar like the enhanced for loop makes a surprising different.

  5. Back to top

    very bad article

    by Ahmet A. Akin

    Java5 is out for two years now, why aouthor insists using Java 1.4? Grovy is a scripting language, it is expected to be less verbose. But author, posibly trying to prove his point, deliberately writes java code extremeley verbose. such as :

    - the whole iterator code can be written in two lines with java 5
    - You do not need to write blah.toString() if you want to write it to standat out.
    - you dont need to put an extra empty constructor.
    - if gorrvy properties are public, why java ones are private?

  6. Back to top

    Re: very bad article

    by Ronald Miura

    - if gorrvy properties are public, why java ones are private?

    From the article:
    The Groovy version is much, much smaller because Groovy's default property semantics automatically define a private field with public accessors and mutators. For example, the property model from above now has the equivalent of a getModel() and setModel() method automatically defined.

  7. Back to top

    Re: very bad article

    by G Giese

    So all fields/attributes in Groovy are automatically private and automatically have get/set methods generated for them? All the get/set stuff is overblown if you ask me -- it's ok to have public fields if you *design* for it. But we're dug in so far that tool/library support almost requires get/set for every attribute of a class.

    I noticed the Groovy toString() version left out weight and status. Also, the Java version had "this." sprinkled everywhere. I never use "this." if I can help it (do it like he did in the Groovy example - call the parameter "newXYZ".

    Comparing productivity based on code size is only somewhat helpful. Groovy's benefit comes mainly from it's more dynamic nature. Certain syntactic elements are nice, too. Until lots of IDEs support it for highlighting, auto-complete, debugging, etc. then it's only useful for smaller stuff, but it definitely has potential. It will be interesting to see what happens with the new Scripting JSR and the languages Sun will support with it, such as their recent purchase (JRuby, right?)

  8. Back to top

    Re: very bad article

    by Rod Johnson

    But we're dug in so far that tool/library support almost requires get/set for every attribute of a class.

    Well, JavaBean properties are certainly conveniently supported in IDEs: easy to generate, visualize etc. But good frameworks should not require the use of JavaBean properties. For example, with any good ORM framework, you can (and should) persist fields rather than properties, providing meaningful constructors to ensure testability. Similarly, with Spring and PicoContainer (and, I think, HiveMind) you can inject via constructors if you wish to use DI without property syntax. With Spring you can also construct via static or instance factory methods, which may have arguments. So framework/tool issues should not really dictate how to author a class.

    The C# attribute syntax, while explicit, is a bit more rigorous than the Java form, which is merely a convention, not a language feature.

  9. Back to top

    Groovy code size benefits

    by Paul King

    I mostly gain code reductions using Groovy due to:


    • * no need for interfaces because of duck-typing

    • * compact builder syntax

    • * closures especially closures vs inner classes

    • * powerful language features such as built-in regex support

    • * powerful libraries such as SOAP, SQL, etc.

    • * built-in testing/mocking support

    • * GStrings

    • * Metaclass facilities to override getters/setters and more at a higher level and support DSLs

    • * named and optional method parameters

    • * more standard features not requiring imports



    Just to name a few.

    Getters/setters are a small win even over Java 5 but they are only minor. I am not sure they would make my top ten.

    I write lots of Java and quite a bit of Groovy and the Groovy is usually a large percentage smaller if not several times smaller.

  10. Back to top

    Re: Spring example

    by Paul King

    For "Groovy in Action" I wrote similar examples for Spring 2.0. It includes examples illustrating:


    • * wiring Groovy beans with Spring

    • * dynamic compilation of Groovy scripts through the Groovy factory mechanism

    • * refreshable beans

    • * inline scripts within the configuration file



    Chapter 11 contains these examples and is available in early access form at: www.manning.com/koenig/

  11. Back to top

    Re: Spring example

    by Rod Johnson

    Paul, thanks for the detail. I agree regarding your points where Groovy can be more concise: obviously properties are just a small part of the whole.

Educational Content

New-age Transactional Systems - Not Your Grandpa's OLTP

John Hugg discusses high volume transaction processing applications with high and low frequency profiles, and how VoltDB can be used for that purpose.

Cool Code

Kevlin Henney examines code samples to see what can be learned from them starting from the premise that one won’t write great code unless he knows how to read it.

Collaboration: At the Extremities of Extreme

Jason Ayers share the observations he made watching a team of developers collaborating in real time on the same code base, pushing XP, pair programming and continuous integration to their extremes.

Yesod Web Framework

Michael Snoyman presents Yesod, a web framework written in Haskell and containing a web server, templating, ORM, libraries (templating, gravatar, etc.).

Transactions without Transactions

Richard Kreuter and Kyle Banker on how to avoid classical RDBMS transactional systems by using compensation mechanisms, transactional messaging or transactional procedures.

Attila Szegedi on JVM and GC Performance Tuning at Twitter

Attila Szegedi talks about performance tuning Java and Scala programs at Twitter: how to approach GC problems, the importance of asynchronous I/O, when to use MySQL/Cassandra/Redis, and much more.

10 tips on how to prevent business value risk

One category of risk that project teams need to ensure they address is business value failure – delivering a product that fails to provide value for the business investor.

Interview: Software Systems Architecture: Working With Stakeholders Using Viewpoints and Perspectives

InfoQ spoke to the authors of Software Systems Architecture on a couple of new topics, the System Context viewpoint and Agile, which have been added to the second edition.