Analytics

Monday, February 21, 2011

5 Handy Groovy Shortcuts

Groovy's main advantage over Java programming is the ability for a developer to implement a solution in fewer lines of code. Groovy's idioms produce concise, short, and clean code. Of course, on first look the code may look strange to a Java developer. But once you learn Groovy's shortcuts you realize the value of consciseness and how less noise produces easier maintenance of code. To me, this is simple: "Since there is less code to look at, there is less code to understand. Learn the shortcuts and idioms and produce less code to do more."

Over the last year, I adopted Groovy as an enterprise implementation language. Here are 5 Groovy programming shortcuts that I found to be very handy. They are listed as tests, in the model of TDD.

Spread Dot Operator

The spread dot operator calls a method on every item in a collection. Upon the invocations, it creates a new list from the return items.  So instead of looping through a collection to make a call on each object, use the spread dot operator.

Let's say we want to get the first 3 letters of each username:

    void testSpreadDot() {
      def emails = ["nirav@yahoo.com", "bob@gmail.com", "jacob@msn.com"]
      def firstThreeLetters = emails*.getAt(0..2)
      assertEquals(firstThreeLetters, ["nir", "bob", "jac"])
    } 
This is very useful when utilizing several common design patterns or just plan old polymorphism. You are able to call an interface many times with minimal code.