David Sills's muse is fueled by Bach, Beethoven, and Brahms (and Berlioz and Boulez). He has no life, which comports well with the über-geekitude to which he aspires. He reads and writes fitfully in English, Spanish, French, German, Italian (mostly medieval), C, VB, Perl.... Oh, and Java and XSLT, lots and lots of Java and XSLT. Trained somewhere in darkest Central America, he works today at DataSource, Inc., on the product team for the CASE tool Jetson.
| Author(s) | Dierk König, with Andrew Glover, Paul King, Guillaume Laforge, and Jon Skeet |
|---|---|
| Publisher | Manning Publications Co |
| PubDate | 2007 |
| Reviewer | David Sills |
Groovy is a new language, usually described as a scripting language. This may be a bit of a misnomer, as scripting languages are typically thought of as being interpreted line-by-line, while Groovy scripts are fully compiled into Java bytecode before execution. One way of thinking of Groovy is to say Groovy is Java. Its syntax is simpler and more expressive; it comes with a nifty toolkit that contains some tremendous time- and effort-savers; it makes a lot of hard problems much easier; but in the end it is Java and a powerful tool Java developers would do well to master.
Groovy in Action is among the first books taking on the task of explaining this new language to potential users. These include anyone with any interest in simplifying their code, easing testing, or developing large-scale applications that can be maintained (and if you're not on this list, why not?). It aims high, at comprehensive coverage of as many aspects of the Groovy language as possible, and if it falls just a little short of perfection, it does very, very well indeed.
A unique aspect of the book permeates the examples: the book is put together from a template with placeholders for the code examples. The latter are actually run (tested) when the book is assembled, and since the examples use assertions to test whether or not they were successful, we can be certain they worked, as otherwise the book wouldn't have been printed! This sort of guarantee of accuracy is worth its weight in gold. No wondering whether the examples have a typo; no looking up an errata list at the book website; just clean, well-tested code.
And what examples! The authors have not flinched from tackling some decidedly non-trivial issues in their pursuit of examples that would really reveal the features and utility of the language. It is astonishing to see how wide a range of applications Groovy can tackle and how successfully it can simplify and clarify code that in Java could easily become prohibitively complex.
The prose style is engaging and highly readable; the author's voice is never excessively prominent. This isn't a collection of opinions, but it does fairly shout excitement about the possibilities it describes. One feels it a work of proselytization in the best sense, a work that radiates an infectious enthusiasm about a new and useful discovery, and that ignites a corresponding enthusiasm in the reader.
Chapter 1 introduces Groovy and how it might fit the needs of various categories of potential users. It discusses two tools that come with the Groovy distribution and provide the ability to execute Groovy commands interactively: the Groovy shell, a command-line shell that executes commands line by line; and the Groovy console, a Swing environment that adds the ability to load and save files. Both tools allow the user to examine the result of Groovy expression execution in the Object Browser, which introspects the API of the result, including additional methods available to the user in Groovy. It also discusses compiling Groovy scripts using groovyc and executing the result in Java from a command line or by using Ant. Finally, there is a section on IDE and code editor support. This latter is out of date already, as rapid progress continues to be made on several IDE plugins, but it points the reader in the right directions.
PART 1 - The Groovy Language
Chapter 2 gives a rapid overview of Groovy basics, beginning with asserts and continuing with other basic concepts, each of which is fleshed out in more detail in later chapters. The effort is to acquaint the user with Groovy's similarities to and differences from Java. In general, Groovy syntax is more concise than Java, but many of the structures are very similar. The idea of closures is introduced and a simple closure is compared to the equivalent Java code, demonstrating that Groovy syntax is also more expressive in that it dispenses with a good deal of Java's syntactical overhead and can get closer to the programmer's intention. A brief review of the internals of Groovy's class generation closes the chapter.
Chapter 3 begins the detailed exploration of Groovy with a discussion of the simple Groovy datatypes. Groovy has no primitives: everything is an object. Groovy allows the type of an object to be explicitly specified, but typing is very different in Groovy than in Java. The concept of duck-typing (as in the adage "if it walks like a duck and quacks like a duck, it's a duck") is natural to Groovy. An object that exposes the required API for a type is that type in effect. Understanding this difference, how Java and Groovy can be used together? And what are the uses of static versus dynamic typing? These are points to which the authors return several times, concluding that each has its place. Since everything in Groovy is an object, operators are implemented as method calls, and as such can be overridden as needed. The remarkable GString (a Groovy extension of java.lang.String that provides a lot more useful functionality) is introduced. Groovy's built-in support for regular expressions is discussed, as is working with number values.
Chapter 4 explores the Groovy collection datatypes: ranges, lists, and maps. Of these, ranges have no cognate in Java, but are intuitively understood. Much of the material here will be familiar to Java programmers, but during the discussion of additions of useful syntactic sugar and of the ability to apply closures to iterating over a collection datatype, the true power of Groovy begins to dawn.
Chapter 5 provides a fuller treatment of closures. Closures are simply a chunk of code as an object, which can take parameters and return a result just like a Java method (in fact, methods can actually be reused as closures). A brief discussion comparing some uses of closures with comparable Java implementations makes it clear why language-level support for this concept is so powerful. A closure is an elegant means of encapsulating an algorithm, but more than that it plays to Groovy's expressivity by simplifying and clarifying the programmer's intention. This makes the resulting code more maintainable. A brief look at the utility of closures in realizing several common design patterns closes the chapter.
Chapter 6 begins by discussing conditionals and "the Groovy truth." This extends well beyond Java's boolean values to incorporate definitions applying to strings, collections, and other Groovy types. These are all quite natural and easily remembered. This definition of what it means to be true and false, of course, has significant impact on conditional structures. The switch statement, which in Java has somewhat limited use, becomes a far more powerful tool, especially when it is remember that the switch statement is a method call that can be overridden. Switch evaluation examples include whether or not a value is in a range, whether it is of a particular class, or whether it satisfies a regular expression or closure. Loops are more similar to Java syntax (although the basic Java for loop is not supported in Groovy, but replaced with something not unlike the foreach loop of Java 5). Exiting a loop, both in normal cases and where exceptions must be thrown, is briefly mentioned. The latter is particularly tricky when using a Groovy class from a Java class.
Chapter 7 - Having completed a survey of the main features of Groovy syntax, it is time to learn how to declare and manage classes and their component parts in Groovy. This is a large chapter, as Groovy provides a number of special features. Declaration of fields, methods, and constructors is shown: particularly useful is the use of named parameters in constructors, which allows for more flexibility in constructor declaration. A valuable addition to Java syntax is the safe dereferencing operator ?, which encapsulates a null check on the object before calling a method. (Null-pointer exceptions, goodbye and good riddance!) Organization of Groovy files is discussed, and potential classloader issues are reviewed. GroovyBeans (think JavaBeans with lots of convenience features) are discussed, as is Expando, the incredible dynamic class that can accept new methods at runtime. The rules of GPath, the Groovy syntax for object tree navigation, allow for a very precise and flexible syntax, even incorporating the idea of finders in the syntax using closures and the grep operator. The spread operator allows for easy use of the contents of a collection (as opposed to the collection itself). The concept of mix-in categories allows even more flexibility in dynamic runtime behavior. All this dynamic behavior is possible because of Groovy's Meta-Object Protocol (MOP), which is explained briefly as background.
PART 2 - Around the Groovy Library
Chapter 8 explores the Groovy concept of builders. Builders implement the eponymous design pattern to help work with hierarchical structures. They can also be looked at as a way of creating domain-specific languages (DSLs) by simplifying common tasks in some situations. DSLs are currently enjoying a lot of interest, and Groovy makes them quite easy. Examples include a selection of the major out-of-box builders: NodeBuilder, MarkupBuilder, AntBuilder, and SwingBuilder. Following these, an example of a custom builder is presented.
Chapter 9 discusses a variety of useful basics for working with Groovy in the real world. Details for working with arbitrary objects in Groovy are supplied. Working with files and other I/O is discussed. Threading in Groovy is considerably simplified by the fact that closures implement Java's Runnable interface and can therefore be used directly in new threads. Groovy has its own templating language, not dissimilar to that used in JSPs or Velocity templates. This is just one of a variety of ways to simplify the dynamic creation of strings, each useful in the right situation. One situation where templates can be useful is in Groovlets and Groovy Server Pages (GSPs), Groovy's method of handling web applications. Like servlets and JSPs, these technologies serve as a building block for more complex structures in web frameworks such as Grails.
Chapter 10 covers Groovy's database programming features. As might be expected by now, the rough but more expressive equivalents to standard Java JDBC are only the tip of the iceberg. Groovy's dynamic features are on display in the DataSet, which allows some work with databases without SQL. The chapter concludes with an example of a database access layer using data access objects (DAOs), discussing architectural and implementation issues. There is a brief mention of Groovy Object-Relational Mapping (GORM) in Grails.
Chapter 11 discusses integration of Java and Groovy. These can involve a variety of Groovy execution engines, including the GroovyShell and the GroovyScriptEngine. The GroovyClassLoader is explored, as well as the security model for running Groovy with Java. Two methods to increase the dynamic nature of Groovy/Java integration are presented: integration of Groovy into the well-known Spring framework, and the new JSR-223 scripting language integration mechanism in Java 6. Finally, considerations for selecting integration strategies for Groovy and Java are summarized.
Chapter 12 explores Groovy's built-in support for XML, which is considerable. It begins with the basics of using XML in Groovy. These include using Groovy's XMLParser or XMLSlurper classes to create a DOM as a one-liner and to manipulate it after creation. SAX and StAX processing are discussed, as well. Examples are presented of using these mechanisms to model XML processing as tree-like or streaming, either of which may be useful depending upon the size of the XML document and the needs of your application. Integration with a more conventional XML mechanism, XPath, is discussed. Finally, the use of XML APIs for distributed processing is presented, with discussion of RSS, ATOM, REST, XML-RPC, and finally SOAP. Since the last is a bit more cumbersome to work with than the others, a toolkit separate from the standard Groovy distribution is available: GroovySOAP. This simplifies both consuming and publishing SOAP web services, especially as GroovySOAP contains a SoapServer class that provides a platform upon which a web service can be published easily.
PART 3 - Everyday Groovy
Chapter 13 contains tips and tricks for using Groovy in real-life situations. This practical advice, while not fitting into any particular category, will prove invaluable even to those with some Groovy experience.
Chapter 14 details Groovy's support for unit testing, beginning with the GroovyTestCase. It continues with more and more elaborate testing mechanisms, including the use of duck-typed substitution to isolate your code from that of classes upon which it depends. Owing to Groovy's typing mechanism, any object that simulates the API of a class upon which yours depends can be substituted for testing purposes. This naturally leads to a discussion of stubs and mocks, which can be implemented using classes imaginatively named StubFor and MockFor (each takes a Class in its constructor, so they read well in English). Finally, more complex cases may require Groovy's GroovyLogTestCase, which allows the test to write to a log as it goes. The logged output can then be examined to ensure test success. A discussion of unit-test integration with IDEs, Ant, and Maven concludes the chapter.
Chapter 15 is devoted to working in Windows environments using the Groovy add-on called Scriptom. This supports using Groovy to control COM and ActiveX objects. Examples begin with Microsoft Word and Excel and progress to working with the Windows registry and WScript.Shell. No matter the simplicity of the example, integration of Groovy into the Windows world can turn tricky, but with the foundation of this chapter, you'll have the tools to essay it successfully.
Chapter 16 presents Grails, a web application framework that is built around Groovy. As this reviewer is simultaneously reviewing A Definitive Guide to Grails, little more needs to be said about this chapter except that it certainly whets the appetite for fuller fare, which the other book provides in abundance.
Appendices - These cover miscellaneous quick look-up topics like installation, Groovy language information, the GDK API, and quick code examples that distill the examples already seen. And remember, they all work, or the book wouldn't have been printed!
The material is very well organized for a straight read-through (I might have placed the section on XML a bit earlier, but that's an extremely minor cavil). Returned to later, however, its organization might be a trifle less useful, for since several points (for example, closures) are returned too again and again, each time in more detail, as a reference the book might be less than ideal. Balancing this, however, is the most useful and oft-ignored part of any such book: a well-made, comprehensive index.
For those who prefer a more textbookish approach, this book may seem a little casual; but if you like to practice what is being preached as you read, you really could hardly do better. This book is therefore squarely in the line of other books in Manning's distinguished "In Action" series. It will grace my bookshelf for many a year.
| Relevance | |
|---|---|
| Readability | |
| Overall | |
Groovy: http://groovy.codehaus.org/
GroovySOAP: http://docs.codehaus.org/display/GROOVY/Groovy+SOAP
Grails: http://grails.codehaus.org/
Scriptom: http://groovy.codehaus.org/COM+Scripting
JSR-223: http://jcp.org/en/jsr/detail?id=223
This book's website: http://www.manning.com/koenig/
The website for another text on Groovy, Groovy Programming: http://books.elsevier.com/us//computerscience/us/subindex.asp?maintarget=&isbn=9780123725073
The Groovy mailing lists (you must get on at least the Groovy User List: it's a trip, and you can see just how active this community really is!): http://groovy.codehaus.org/mail-lists.html