Your Way to Groovy
|“One main factor in the upward trend of animal
life has been the power of wandering.”|
-Alfred North Whitehead
Welcome to the world of Groovy.
You've heard of Groovy on blogs and mailing lists. Maybe you've seen a snippet here and there. Perhaps a colleague has pointed out a page of your code and claimed the same work could be done in just a few lines of Groovy. Maybe you only picked up this book because the name is catchy. Why should you learn Groovy? What payback can you expect?
Groovy will give you some quick wins, whether it's by making your Java code simpler to write, by automating recurring tasks, or by supporting ad-hoc scripting for your daily work as a programmer. It will give you longer-term wins by making your code simpler to read. Perhaps most important, it's fun to use.
Learning Groovy is a wise investment. Groovy brings the power of advanced language features such as closures, dynamic typing, and the meta object protocol to the Java platform. Your Java knowledge will not become obsolete by walking the Groovy path. Groovy will build on your existing experience and familiarity with the Java platform, allowing you to pick and choose when you use which tool-and when to combine the two seamlessly.
If you have ever marveled at the Ruby folks who can implement a full-blown web application in the afternoon, the Python guys juggling collections, the Perl hackers managing a server farm with a few keystrokes, or Lisp gurus turning their whole codebase upside-down with a tiny change, then think about the language features they have at their disposal. The goal of Groovy is to provide language capabilities of comparable impact on the Java platform, while obeying the Java object model and keeping the perspective of a Java programmer.
This article provides background information about Groovy and everything you need to know to get started. It starts with the Groovy story: why Groovy was created, what considerations drive its design, and how it positions itself in the landscape of languages and technologies. The next section expands on Groovy's merits and how they can make life easier for you, whether you're a Java programmer, a script aficionado, or an agile developer.
We strongly believe that there is only one way to learn a programming language: by trying it. We present a variety of scripts to demonstrate the compiler, interpreter, and shells, before listing some plug-ins available for widely used IDEs and where to find the latest information about Groovy.
By the end of this two part series, you will have a basic understanding of what Groovy is and how you can experiment with it.
We–the authors, the reviewers, and the editing team–wish you a great time programming Groovy and using this article for guidance and reference.
The Groovy story
At GroovyOne 2004–a gathering of Groovy developers in London–James Strachan gave a keynote address telling the story of how he arrived at the idea of inventing Groovy.
Some time ago, he and his wife were waiting for a late plane. While she went shopping, he visited an Internet café and spontaneously decided to go to the Python web site and study the language. In the course of this activity, he became more and more intrigued. Being a seasoned Java programmer, he recognized that his home language lacked many of the interesting and useful features Python had invented, such as native language support for common datatypes in an expressive syntax and, more important, dynamic behavior. The idea was born to bring such features to Java.
This led to the main principles that guide Groovy's development: to be a feature rich and Java friendly language, bringing the attractive benefits of dynamic languages to a robust and well-supported platform.
Figure 1 shows how this unique combination defines Groovy's position in the varied world of languages for the Java platform.¹ We don't want to offend anyone by specifying exactly where we believe any particular other language might fit in the figure, but we're confident of Groovy's position.
Figure 1: The landscape of JVM-based languages. Groovy is feature rich and Java friendly-it excels at both sides instead of sacrificing one for the sake of the other.
Some languages may have a few more features than Groovy. Some languages may claim to integrate better with Java. None can currently touch Groovy when you consider both aspects together: Nothing provides a better combination of Java friendliness and a complete range of modern language features. Knowing some of the aims of Groovy, let's look at what it is.
What is Groovy?
The Groovy web site (http://groovy.codehaus.org) gives one of the best definitions of Groovy: "Groovy is an agile dynamic language for the Java Platform with many features that are inspired by languages like Python, Ruby and Smalltalk, making them available to Java developers using a Java-like syntax."
Groovy is often referred to as a scripting language-and it works very well for scripting. It's a mistake to label Groovy purely in those terms, though. It can be precompiled into Java bytecode, be integrated into Java applications, power web applications, add an extra degree of control within build files, and be the basis of whole applications on its own-Groovy is too flexible to be pigeon-holed.
What we can say about Groovy is that it is closely tied to the Java platform. This is true in terms of both implementation (many parts of Groovy are written in Java, with the rest being written in Groovy itself) and interaction. When you program in Groovy, in many ways you're writing a special kind of Java. All the power of the Java platform-including the massive set of available libraries-is there to be harnessed.
Does this make Groovy just a layer of syntactic sugar? Not at all. Although everything you do in Groovy could be done in Java, it would be madness to write the Java code required to work Groovy's magic. Groovy performs a lot of work behind the scenes to achieve its agility and dynamic nature. As you read this article, try to think every so often about what would be required to mimic the effects of Groovy using Java. Many of the Groovy features that seem extraordinary at first-encapsulating logic in objects in a natural way, building hierarchies with barely any code other than what is absolutely required to compute the data, expressing database queries in the normal application language before they are translated into SQL, manipulating the runtime behavior of individual objects after they have been created-all of these are tasks that Java cannot perform. You might like to think of Groovy as being a "full color" language compared with the monochrome nature of Java-the miracle being that the color pictures are created out of lots of carefully engineered black and white dots.
Let's take a closer look at what makes Groovy so appealing, starting with how Groovy and Java work hand-in-hand.
Playing nicely with Java: seamless integration
Being Java friendly means two things: seamless integration with the Java Runtime Environment and having a syntax that is aligned with Java.
Figure 2 shows the integration aspect of Groovy: It runs inside the Java Virtual Machine and makes use of Java's libraries (together called the Java Runtime Environment or JRE). Groovy is only a new way of creating ordinary Java classes-from a runtime perspective, Groovy is Java with an additional jar file as a dependency.
Figure 2: Groovy and Java join together in a tongue-and-groove fashion.Consequently, calling Java from Groovy is a non-issue. When developing in Groovy, you end up doing this all the time without noticing. Every Groovy type is a subtype of java.lang.Object. Every Groovy object is an instance of a type in the normal way. A Groovy date is a java.util.Date, and so on. Integration in the opposite direction is just as easy. Suppose a Groovy class MyGroovyClass is compiled into a *.class file and put on the classpath. You can use this Groovy class from within a Java class by typing
new MyGroovyClass(); // create from Java
In other words, instantiating a Groovy class is identical to instantiating a Java class. After all, a Groovy class is a Java class. You can then call methods on the instance, pass the reference as an argument to methods, and so forth. The JVM is blissfully unaware that the code was written in Groovy.
The second dimension of Groovy's friendliness is its syntax alignment. Let's compare the different mechanisms to obtain today's date in Java, Groovy, and Ruby in order to demonstrate what alignment should mean:
import java.util.*; // Java Date today = new Date(); // Java today = new Date() // a Groovy Script require 'date' # Ruby today = Date.new # Ruby
The Groovy solution is short, precise, and more compact than normal Java. Groovy does not need to import the java.util package or specify the Date type; moreover, Groovy doesn't require semicolons when it can understand the code without them. Despite being more compact, Groovy is fully comprehensible to a Java programmer.
The Ruby solution is listed to illustrate what Groovy avoids: a different packaging concept (require), a different comment syntax, and a different object-creation syntax. Although the Ruby way makes sense in itself (and may even be more consistent than Java), it does not align as nicely with the Java syntax and architecture as Groovy does.
Now you have an idea what Java friendliness means in terms of integration and syntax alignment. But how about feature richness?
Power in your code: a feature-rich language
Giving a list of Groovy features is a bit like giving a list of moves a dancer can perform. Although each feature is important in itself, it's how well they work together that makes Groovy shine. Groovy has three main types of features over and above those of Java: language features, libraries specific to Groovy, and additions to the existing Java standard classes (GDK). Figure 3 shows some of these features and how they fit together. The shaded circles indicate the way that the features use each other. For instance, many of the library features rely heavily on language features. Idiomatic Groovy code rarely uses one feature in isolation- instead, it usually uses several of them together, like notes in a chord.
Figure 3: Many of the additional libraries and JDK enhancements in Groovy build on the new language features. The combination of the three forms a "sweet spot" for clear and powerful code.Unfortunately, many of the features can't be understood in just a few words. Closures, for example, are an invaluable language concept in Groovy, but the word on its own doesn't tell you anything. We won't go into all the details now, but here are a few examples to whet your appetite.