
|
Groovy – a First Look![]() Documentation and ExamplesThe Groovy web site provides wiki style documentation, which can also be downloaded and is available as a PDF. Most of the information you will need is there, but it's not particularly well organised. Some of it refers to earlier versions (and syntax) of Groovy, which can be problematic. The “Getting Started Guide” section will do just that, it looks at installing Groovy and running the infamous 'Hello World' script. The various IDE plugins are covered in “IDE support”, I installed the Groovy plugin for Eclipse. The “User Guide” section runs through the most important aspects of the language, and the “Cookbook Examples” section provides both examples and a first look at some serious Groovy code.
After a couple of days with the wiki PDF, I needed something a little more organised. Fortunately, the Pragmatic Programmers have just issued a couple of Groovy books, though they're still in beta and currently only available in PDF, and will be until March 2008. The first is “Programming Groovy”, by Venkat Subramaniam. Unfortunately, as of writing (January 2008) the book is only about half finished. The second book is “Groovy Recipes”, by Scott Davis. Scott's book seems pretty complete, so that's what I've been using for the time being.
The “Wow!” FactorsIf you're a long time Java programmer like myself, and have strayed off the “one true path”, by using dynamic languages such as Ruby, then you'll understand the “Wow!” factors. Ruby has so many elegant features that I've found going back to Java a real struggle. But it's also a huge problem trying to sell Ruby (and JRuby) in the JavaWorld. The Groovy team seem to have understood that problem right from the start. What they've produced is something which can start out very close to pure Java syntax, and then move on towards idiomatic Groovy. That way, the learning curve is not so steep.
So, from a hectic few days of Groovy programming, here is a short list of “Wow!” factors that I really like.
The Java to Groovy TranspositionLet's see just how easy it is to move to idiomatic Groovy from idiomatic Java. Here's a simple 'Hello World' application which simply lists it's arguments, this is HelloWorld.groovy:
public class HelloWorld {
public static void main(String[] args) {
System.out.println("Hello World!");
for(String arg : args) {
System.out.println(arg);
}
}
}
Looks pretty much like Java, doesn't it? But Groovy can take us a little further, firstly because it adds a static println() method to Object, and secondly because semi-colons are optional, and thirdly because the compiler knows that the class name matches the filename:
public static void main(String[] args) {
println("Hello World!")
for(String arg : args) {
println(arg)
}
}
That's a little less typing. Now Groovy also knows that any code outside of a method needs to be wrapped in a static main method. Groovy won't be too troubled by missing parentheses in the method calls either. It's also a dynamic language, so we don't really need to tell it that arg is a String. Oh, and it also provides an each() method for collections, so:
println "Hello World!"
args.each { arg ->
println arg
}
That's about the least amount of typing you'll need. But what about the compiled class file? What does that look like to Java? Well, it looks like this (when decompiling the bytecode):
![]() Which is pretty close to what you'd have got writing a pure Java class.
Groovy BeansWe can continue that type of compactness when writing plain old Groovy objects (POGOs), which are very much like POJOs, but without the boilerplate baggage:
package net.sf.bifocal.table
class Cell {
Table parent = null
Row parentRow = null
String styleName = null
int span = 1
String valueType = "string"
def value = null
Map properties = [:]
Cell() {
}
Cell(Table table, Row row) {
parent = table
parentRow = row
}
}
Well, we're used to the missing semicolons by now. The def keyword defines a property or method – in this case we'll have an Object type for value. Note also how easy it is to create an empty Map object – just [:]. But is this GroovyBean really a JavaBean? Again let's take a look at the bytecode:
![]() Looks like one to me. Wow! Look at all those getters and setters. That's a very low signal to noise ratio.
Heredocs or Triple QuotesWhat if you needed a string like this:
<office:automatic-styles>
<style:page-layout style:name="pm1">
<style:page-layout-properties fo:page-width='21.001cm' fo:page-height='29.7cm'
fo:margin-bottom='1.499cm' fo:margin-left='2.499cm' fo:margin-right="2.499cm">
<style:background-image/>
<style:columns fo:column-count="1" fo:column-gap="0cm"/>
</style:page-layout-properties>
<style:header-style/>
</style:page-layout>
</office:automatic-styles>
Care to write that in Java? Try this in Groovy:
String openDocContent = '''
<office:automatic-styles>
<style:page-layout style:name="pm1">
<style:page-layout-properties fo:page-width='21.001cm' fo:page-height='29.7cm'
fo:margin-bottom='1.499cm' fo:margin-left='2.499cm' fo:margin-right="2.499cm">
<style:background-image/>
<style:columns fo:column-count="1" fo:column-gap="0cm"/>
</style:page-layout-properties>
<style:header-style/>
</style:page-layout>
</office:automatic-styles>'''
Wasn't too difficult was it? This makes unit testing XML so much easier.
Other FavouritesAlthough you've got property getters and setters, Groovy lets you use the (private) property names instead, so:
value = myTable.getRow().getCell().getValue(); becomes:
value = myTable.row.cell.value And what if the table, row, cell, or value are null? This:
if (myTable != null) {
myRow = myTable.getRow();
if (myRow != null) {
myCell = myRow.getCell();
if (myCell != null) {
myValue = myCell.getValue();
}
}
}
becomes:
myValue = myTable?.row?.cell?.value That's Groovy's safe dereferencing.
Finally, even the ternary expression gets a reworking:
myValue = myValue != null ? myValue : myDefaultValue; becomes:
myValue = myValue ?: myDefaultValue Here, by the way, myValue evaluates as true when it's not null as far as Groovy is concerned.
ContactsSyger can be contacted for consultancy work on any of the topics mentioned in this article, by sending an email to info@syger.it.
|
Tag cloud: |