SpringOne Americas

Private Events

Blogs

View all Blogs >>
  • Andrew Glover

    Co-author of "Continuous Integration"

    Every once in a while the topic of code coverage surfaces, which more»

  • Stuart Halloway

    CEO of Relevance

    Programmers coming to functional languages for the first time cannot imagine life without variables. I address this head-on in the more»

  • Richard Monson-Haefel

    VP of Developer Relations, Curl Inc.

    more»

  • Neal Ford

    Application Architect at ThoughtWorks, Inc.

    The lowly whiteboard is one of my favorite tools for design work on projects: you can stand in front of it as a group, you can easily play... more»

  • Michael Nygard

    Agile technology leader and dynamicist

    Sizing, Danish Style Folks in telecommunications and operations research have used Erl more»

  • Matt Raible

    Creator of AppFuse and author of Spring Live

    It's been three weeks since I joined the realm of the unemployed. Fortunately, I more»

  • Alex Miller

    Sr. Engineer with Terracotta Inc.

    Or maybe that should be “a bit of final advice”. :) There was a more»

  • Vladimir Vivien

    Software Engineer / Consultant

    I finally downloaded the latest JDK 6 u 10 (download) recently. This is a significant re more»

  • Scott Leberknight

    Chief Architect at Near Infinity

    Re nae Bair's post on The Ranting Rubyis more»

  • Graeme Rocher

    Project Lead of the Grails Project & CTO of G2One

    Those crazy guys over at the Grails podcast interviewed me about various things ranging from being part of more»

  • Ted Neward

    Enterprise, Virtual Machine and Language Wonk

    Dustin Campbell, a self-professed "IDE guy", is speaking at the .NET Developer's Association of Redmond this evening, on the future of... more»

  • Pratik Patel

    Enterprise Architect

    There's been a 'backlash' of sorts brewing in the Java developer community over the past 2 years. From talking to my developer buddies around... more»

  • Howard Lewis Ship

    Creator of Tapestry and HiveMind

    Seems like the Mac has a huge number of RSS readers. For a while I was using Vienna, but it stopped working after a recent update (no blogs... more»

  • Mike Levin

    Software Developer specializing in Web2.0 websites

    (photo from more»

  • Brian Pontarelli

    Founder of Inversoft

    Just figured out how to get git tab completion working in zsh on a Mac. Turns out that the completion scripts use a bunch of extra git... more»

  • Erik Doernenburg

    Principal Consultant @ Thoughtworks

    If you are somebody who writes code you probably know that moment when you look at some code you didn’t write, or some code you wrote a... more»

  • Kirk Knoernschild

    Software Developer & Mentor

    more»

  • Brian Goetz

    Author of Java Concurrency in Practice

    I live in an AT&T-free state, so I have not had access to the cult that is iPhone. But recently, in preparation for AT&T moving... more»

  • Matthew Bass

    Software Developer & Entrepreneur

    Can Sphinx and foxy fixtures place nicely together? Due to the way Sphinx indexing works, foxy fixtures will often slow down the indexing... more»

  • Jason Rudolph

    Author of Getting Started with Grails

    I had the more»

  • Ryan Shriver

    Business and Technology Consulting

    more»

  • Nathaniel Schutta

    Author, speaker, software engineer focused on user interface design.

    Today we learned something important, the NTSB announced the more»

  • Jeff Brown

    SpringSource Engineering And Professional Services - Groovy and Grails Developer

    Strange enough title.Let's start with a hypothetical conversation between a geeky developer and his much less geeky wife: more»

  • Jared Richardson

    Agile coach and co-author of Ship It

    Jurgen Appelo has an ongoing interview series on his blog. He's published a lot of very smart people and I'm honored to squeak in too! ;) more»

  • David Bock

    Principal Consultant, CodeSherpas Inc.

    I have been setting up a rock-solid server cluster for a client and ran into an interesting issue trying to install Phusion Passenger onto... more»

  • Pramod Sadalage

    Co-author of "Refactoring Databases:Evolutionary Database Development"

    Consider this Hibernate mapping @Column(name = "qReferenceId") public Long getQReferenceId() { return qReferenceId; more»

  • Craig Walls

    Author of Spring in Action

    At one time not too long ago, I wasn't a big fan of annotations. But then I let my guard down and even started liking them. But now I'm... more»

  • Kenneth Kousen

    President of Kousen IT, Inc.

    In this entry in my “Making Swing Groovy” series, I want to talk about threading issues. Specifically, more»

  • Venkat Subramaniam

    Founder of Agile Developer, Inc.

    I wrote a four part article for Java World on creating DSLs in Java and Groovy. For your convenience, I decided to list the links to those... more»

  • Jason Harwig

    Senior Software Engineer at Near Infinity

    The most popular entry I've written at Near Infinity has been the more»

  • John Heintz

    Principal Consultant with New Aspects of Software

    In a recent discussion interview questions came up, here's my favorite one.To set some context this question is designed to gauge the abst more»

  • Mark Johnson

    Director of Consulting at CGI

    At the Columbus NFJS show held on July 25-27th during one of the BOF sessions Dave Bock, Scott Davis and I discussed unit tests vs functional... more»

  • Joseph Nusairat

    Author of Beginning JBoss Seam & Co-Author of Beginning Groovy & Grails

    Well i am assuming Apress has the most random site in the world at times.But today only they have our recent book, Beginning Groovy & Grai more»

  • Keith Donald

    Lead of Spring Web and Creator of Spring Web Flow

    I am pleased to announce that Developing Rich Web Applications with Spring, a three-day bootcamp lead by SpringSource engineers on web... more»

  • Pete Behrens

    Organizational Agility Coach

    Marti nig & Associates Methods & Tools group recentl more»

  • Brian Sam-Bodden

    Java author, Ruby geek and Open Source Advocate

    In this installment we are going to build the Dashboard page of the Tempo application. T more»

  • Mark Fisher

    Spring Integration Lead

    In my recent post, I had mentio more»

  • Ron Bodkin

    Chief Software Architect, Quantcast

    I'm looking forward to speaking at The Rich Web Experience conference in San Jose next month. The event runs from September 7th through 9th.... more»

  • Mark Goodwin

    Web Application Security Specialist

    We've already looked at one of the two big problems posed by anti DNS pinning on Java applets; because there's rebinding on the applet and... more»

  • Scott Davis

    Author of "Groovy Recipes" & TDD Expert

    Every time I see a live show at the Denver Botanic more»

  • Romain Guy

    Java User Interface expert.

    more»

  • Ramnivas Laddad

    Author of AspectJ in Action, Principal at SpringSource

    InfoQ.com has published my AOP myths and realities talk recorded at a No Fluff Just Stuff conference. InfoQ.com founded by Floyd Marine more»

  • David Geary

    Author of Graphic Java and co-author of Core JSF

    The 2006 NFJS tour kicked off t more»

  • Kito Mann

    Editor-in-chief of JSF Central and the author of JSF in Action

    I miss the latest.integration keyword from ivy.... more»

  • Jason Hunter

    Author of Java Servlet Programming

    I just posted the JDOM 1.1 release for download. This release includes about 20 improvements and bug fixes. more»

Unadulterated Java is so groovy

Posted by: Andrew Glover on 03/07/2008

Groovy is an alternate language for the JVM– alternate in that Groovy is a simpler, more expressive Java (which, by the way, also happens to work with normal Java). In fact, if you already know Java, you basically know Groovy, man.

definition

Groovy’s syntax is a less strict version of Java’s and adds a few new features here and there. You could say that Groovy’s syntax is terse, which yeilds a highly expressive medium for conveying behavior without a lot of extranous verbiage. But the beauty is that that verbiage isn’t gone– it’s assumed. Hence, Groovy is an unadulterated version of Java, baby.

As a demonstration, here is a hip Java class that represents a song, aptly named Song. As you can imagine, this code exists in a file named Song.java and is located in some sort of package structure (like com.acme.blah).

public class Song {
 private String name;
 private String genre;
 private String artist;

 public String getName() {
  return name;
 }

 public void setName(String name) {
  this.name = name;
 }

 public String getGenre() {
  if(genre != null){
   return genre.toUpperCase();
  }else{
   return null;
  }
 }

 public void setGenre(String genre) {
  this.genre = genre;
 }

 public String getArtist() {
  return artist;
 }

 public void setArtist(String artist) {
  this.artist = artist;
 }
}

This bogue class doesn’t do anything particularly interesting and is basically a JavaBean– but it serves as an excellent demonstration of how you can achieve the same behavior (albeit simple) in Groovy with fewer lines of code.

As a first step, you can make this a Groovy class by just changing the file’s type to .groovy– in fact, Song.groovy as is, will compile just fine with groovyc.

One thing about Groovy is that it is Java without accessibility modifiers (i.e. you don’t have to specify public– everything is assumed to be so unless you say otherwise) and semi-colons. Consequently, I can trim down this class somewhat by removing all semi-colons and public modifiers, baby.

class Song {
 private String name
 private String genre
 private String artist

 String getName() {
  return name
 }

 void setName(String name) {
  this.name = name
 }

 String getGenre() {
  if(genre != null){
   return genre.toUpperCase()
  }else{
   return null
  }
 }

 void setGenre(String genre) {
  this.genre = genre
 }

 String getArtist() {
  return artist
 }

 void setArtist(String artist) {
  this.artist = artist
 }
}

Already, because it’s my bag, Song is getting a bit shorter, but nothing to write home about.

What’s particularly handy in Groovy is the way it treats properties– in this case, Song has 3 (name, genre, and artist). By convention, in Java, if you want to access these values (i.e. via getters and setters) you copasetically create corresponding setProperty and getProperty methods. In Groovy, these accessors are generated for you; consequently, in the Song class, I can remove those methods leaving me with the following code:

class Song {
 private String name
 private String genre
 private String artist

 String getGenre() {
  if(genre != null){
   return genre.toUpperCase()
  }else{
   return null
  }
 }
}

Note that I left in the getGenre method– that’s doing something special.

Be careful though, disco dancers, as in Groovy, if I leave the properties as private Groovy will not generate the accessors– accordingly, the next step is to remove the private modifier on the properties.

class Song {
 String name
 String genre
 String artist

 String getGenre() {
  if(genre != null){
   return genre.toUpperCase()
  }else{
   return null
  }
 }
}

Looking at this code, I can hear the Java faithful grinding their teeth over what appears to be a lack of encapsulation, baby– in fact, in Groovy, you can access the name property directly!

Or do you?

Using a simple GroovyTestCase, I can knock out a quick test to see property access in action:

class SongTest extends GroovyTestCase {

 void testPropertyAccess() {
  def sng = new Song(artist:"Lipps, Inc",
      name:"FunkyTown", genre:"Disco")

  assertEquals("FunkyTown", sng.name)
  assertEquals("FunkyTown", sng.getName())
 }
}

In the code above, I’m grabbing a property either directly or via the getter method– the same, by the way, is true for setting a value. But the question remains, when the property is seemingly accessed directly, does this by pass the getter (or setter)?

One way to find out is to use the getGenre method, right? It does something special– accordingly, the following test case demonstrates hip encapsulation in action:

void testEncapsulatedAccess() {
 def sng = new Song(artist:"Lipps, Inc",
   name:"FunkyTown", genre:"Disco")

 assertEquals("DISCO", sng.genre)
 assertEquals("DISCO", sng.getGenre())
}

Even though the properties in the Song class are not explicitly private, they are acting privately, aren’t they, man?

Going back to the getGenre method on the Song class, it turns out that Groovy also has a handy syntax for null pointer safety, consequently, I can simply that method even further.

class Song {
 String name
 String genre
 String artist

 String getGenre() {
  return genre?.toUpperCase()
 }
}

Groovy also permits dropping return statements– in essence, the last line of a method is assumed as the return value. So, that leaves the getGenre method as:

String getGenre() {
  genre?.toUpperCase()
}

Groovy infers types– for instance, writing String value = "groovy"; is a bit verbose, no? Think about it for a second– String value is superfluous isn’t it? value must be a String as I set it to one, right? Likewise, in Groovy, value is clearly a String (because it is set to a String directly!) without having to give the compiler (or runtime) a hint. Accordingly, you can drop types and replace them with Groovy’s hip def keyword.

class Song {
 def name
 def genre
 def artist

 def getGenre() {
  genre?.toUpperCase()
 }
}

Removing an explicit type does have some consequences though– in this case, given that Groovy is Java, these properties must have some type associated with them. What do you think that type is? Right! java.lang.Object, baby. Consequently, if you were to use this Groovy Song class in Java, the getGenre method will have a return type of Object, not String (unless you explicitly make String the return type).

Applying groovy techniques to Java yields a more effective Java– in this case, the Song class started out at roughly 30 lines of code. Refactoring it down a bit by leveraging Groovy, I ended up with basically 10 lines of code. The code is essentially the same– the only behavioral difference being that Object is now king with method return types (should you use this class in normal Java). But switching out def for String doesn’t add any new lines of code, does it?

Groovy is unadulterated Java– in fact, it’s Java without a lot of Java. Can you dig it, baby?

I also blog at testearly.com | My company is hiring gurus


be the first to rate this blog


About Andrew Glover

Andrew was the founder of Vanward Technologies, which was acquired by JNetDirect in 2005. Subsequently, he served as President of Stelligent Incorporated.

Andrew is the founder of the easyb BDD framework and the co-author of Addison Wesley's "Continuous Integration", Manning's "Groovy in Action" and "Java Testing Patterns". He is an author for multiple online publications including IBM's developerWorks and Oreilly's ONJava and ONLamp portals. He actively blogs about software at thediscoblog.com.