Get’cha Groove On


I’ve been slowly getting back into my Groovy state of mind after immersing in Maven2, Servlets, and J2ME for over a year. If you’re one of those people who can’t stand yet another programming language then this topic is for you. If you’re one of those who think “My language grammar suites me just fine” then step off! I ain’t even tryin’ to holler at you. If you’re one of those people who don’t understand why a language is so important than allow me to elaborate.

Modern languages are about high level expressiveness, getting things done by mirroring the thought more closely which requires less specific steps. For instance: The loop has been done many times over. We don’t want to think loop until I get my desired result. in my variable which is a value equal to the number of files in a directory. We want to express that we are taking some action on each file in a folder. Older style languages pay little if any attention to the need to express the thought of a developer. Rather they organize the mechanics of the syntax to allow re-use of common constructs. if/select/while constructs are being replaced with closures. Code generation and reflection are giving way to Meta Object Protocols. The new thing in town is DSL, which focuses on how easy it is to express the intent of the logic by massaging and bending the syntax of the language.

That said, you can probably tell that I’m going to speak about Groovy for a minute. If you don’t want to learn another language then Groovy is perfect for you! You most likely already know it. Take the following snip for example:

import java.io.File;
import java.util.*;

public List getNamesOfMusicInFolder(File folder) {
   List names = new ArrayList();
   File files = folder.listFiles();
   for(int i = 0; i < files.length(); i++)
      if(files&#91;i&#93;.getName().toLowerCase().endsWith(".mp3")) names.add(files&#91;i&#93;.getName());
   return names;
}
&#91;/sourcecode&#93;

If you can write or figure out code like that then you're already a Groovy programmer. Expert points if you happen to know the Java API. Now why is that so interesting? Because we can groove it up by doing Ruby like stuff with the same familiar programming constructs, APIs and platform that we've been using for years. Start by removing semi colons, Variable declararations and import statements because Groovy makes them unnecessary. 

&#91;sourcecode language="java"&#93;
def getNamesOfMusicInFolder(folder) {
   def names = new ArrayList()
   def files = folder.listFiles()
   for(int i = 0; i < files.length; i++)
      if(files&#91;i&#93;.getName().toLowerCase().endsWith(".mp3")) names.add(files&#91;i&#93;.getName())
   return names
}
&#91;/sourcecode&#93;

Now let's pretend getter and setter methods are properties, because Groovy doesn't care about the difference. And while we're at it we'll use the left shift operator which also doubles as an append operator:

&#91;sourcecode language="java"&#93;
def getNamesOfMusicInFolder(folder) {
   def names = new ArrayList()
   def files = folder.listFiles()
   for(int i = 0; i < files.length(); i++)
      if(file&#91;i&#93;.name.toLowerCase().endsWith(".mp3")) names << file&#91;i&#93;.name
   return names
}
&#91;/sourcecode&#93;

Now use a more modern loop construct:

&#91;sourcecode language="java"&#93;
def getNamesOfMusicInFolder(folder) {
   def names = new ArrayList()
   for(file in folder)
      if(file.name.toLowerCase().endsWith(".mp3")) names << file.name
   return names
}
&#91;/sourcecode&#93;

Wait! Why are we looping at all? Let's pass a closure to the each method. A closure is a chunk of code that the each method executes on each thing:

&#91;sourcecode language="java"&#93;
def getNamesOfMusicInFolder(folder) {
   def names = new ArrayList()
   folder.each( { file -> if(file.name.toLowerCase().endsWith(".mp3")) names << file.name } )
   return names
}
&#91;/sourcecode&#93;

Kinda ugly but remember that parenthisis are optional in Groovy
&#91;sourcecode language="java"&#93;
def getNamesOfMusicInFolder(folder) {
   def names = new ArrayList()
   folder.each { file -> if(file.name.toLowerCase().endsWith(".mp3")) names << file.name } 
   return names
}
&#91;/sourcecode&#93;

And on and on and on, till the break of dawn or at least until we get it down to the beautiful one liner that would cause your average gear head to brag more than <a href="http://tv.yahoo.com/seinfeld/show/the-parking-space/episode/167176">George Castanza grabbing the first parking spot</a>.


new File(dir).listFiles( { dir, file -> file.toLowerCase().endsWith( ".mp3" )  } as FilenameFilter )*.name

What about bindings? Where are the bindings? What are bindings? Bindings are interfaces or APIs that a given platform or framework offers for programmers that use a given language. Groovy is just Java with flava. That means anywhere there’s Java bindings there’s groovy bindings. And since any interface or API can be grooved up that means you can actually modify or add flava to those bindings. More on that in another post.

That’s a small example of what you can do with Groovy. There is a much bigger picture here, the Java platform. Groovy compiles to, runs on, plays well with, the JVM. You don’t need a separate skill set to take advantage of what people from other camps brag about. Java already has several GUI builders, Mattisse being among the best. Java has what I believe is some of the best IDEs ever thought of. (IntelliJ Idea and Eclipse though many complain about Eclipse memory issues.) Java supports presentation engines that regurgitate Flash or AJAX. Java is the king of server deployment simplicity… just plug a spec compliant archive in and go. JVMs are on midranges mainframes, browsers, and mobile devices. (I’m not to crazy about mobile JVMs.) To coin a phrase, “Java is everywhere you wanna be.”

Taking that idea even further, the Groovy camp offers features such as “.Net” interoperability, Windows binaries, and COM scripting that means even on Windows platforms you aren’t that far from native behavior while leveraging the same familiar syntax and VM that uncle Otis grew up with. I could go on forever but I’m gonna take a break now and actually do some Groovy coding. I’ll come back with something we can all admire.

2 thoughts on “Get’cha Groove On

  1. Jeah! I love it! That’s the thing. You start small then eventually build into something that looks like Merlyn’s snip. The only thing I don’t like is the breakdown in readability that comes with regex. RegEx is very powerful but reads like a scroll inscribed in a foreign language dug up from the depths of a cave after being crapped on by twelve elephants in the African sun. Somehow you always have that one archeologist that can make out almost every word while others hold their heads at different angles nod, agree, and pretend to understand.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s