Groovy and Java: a Comparison Groovy’S Resemblance to Java Is Often Quite Striking
Total Page:16
File Type:pdf, Size:1020Kb
APPENDIX ■ ■ ■ The Groovy Language Groovy is an all-purpose programming language for the JVM. It was born in 2003 when James Strachan and Bob McWhirter founded the Groovy project with the goal of creating a glue lan- guage to easily combine existing frameworks and components. Groovy is a language that aims to bring the expressiveness of languages such as Ruby, Lisp, and Python to the Java platform while still remaining Java friendly. It attracted much excitement with these ambitious goals, because the majority of other scripting languages on the Java platform either used an entirely alien syntax and APIs or were simply Java without the need to specify types. Despite its youth, Groovy is a stable, feature-rich language that forms the perfect base for Grails. This is a fantastic achievement, given the limited resources available to an open source project such as Groovy. Groovy was an obvious choice as a platform for the Grails framework, because it provides the necessary underlying infrastructure to create the diverse range of miniature domain-specific languages utilized throughout Grails. ■Note Martin Fowler has written an excellent article about domain-specific languages: http://www.mar- tinfowler.com/bliki/DomainSpecificLanguage.html. What does this mean? Well, the syntax you see used throughout the book has often been magically enhanced and shortened by using a combination of Groovy’s already concise syntax and its support for metaprogramming. Groovy performs a lot of magic under the covers, abstracted away from the developer. This removes the burden from the programmer who would otherwise be required to write reams of unnecessary, repetitive code. Before we start our journey through the diverse syntax offered by Groovy, it is worth understanding how it compares to its cousin Java. In the next section, you will see how seam- lessly Groovy integrates with Java at the syntax level. Groovy and Java: A Comparison Groovy’s resemblance to Java is often quite striking. Some Groovy code is almost indis- tinguishable from Java. If your Groovy code looks too much like Java, you can improve its expressiveness by writing more idiomatic Groovy. Groovy code, when written by an 545 546 APPENDIX ■ THE GROOVY LANGUAGE experienced Groovy developer, typically occupies 40–60 percent fewer lines of code when compared to the equivalent Java. In the following sections, we’ll cover the key similarities and differences between Groovy and the Java language. What’s the Same? Java and Groovy actually have many similarities. This is what makes Groovy so appealing from a Java developer’s perspective. There is no huge mental shift necessary to start working with Groovy. The Groovy syntax can almost be seen as a superset (although this is not the case) of the Java language, with the following taken directly from Java’s syntax: • Keywords and statements • try/catch/finally exception handling • Class, interface, field, and method definitions • Instantiation of objects using the new operator • Packaging and imports • Operators, expressions, and assignment • Control structures • Comments • Annotations, Generics, static imports, and enum types from Java 5 More importantly, though, Groovy shares the same object and runtime model as Java, so the infrastructure that you are operating in (the JVM) is the same. What does this mean? Well, although Groovy is a dynamic language like Ruby or Python, it is not interpreted. All Groovy code, be it executed as a script or a fully qualified class, is compiled down to byte code and then executed. You shouldn’t underestimate the significance of this, because it means that a Groovy class is a Java class and that Groovy and Java can interoperate with each other seamlessly. A Java class can call methods on a class implemented in Groovy without ever knowing any different. So, that’s what is the same; again, we’ve given a brief overview, but really the similarities become obvious quite quickly once you start working with Groovy. Of equal significance, how- ever, is what is different about Groovy. What’s Different? One of the things that makes Groovy different is that a number of things are optional, including parentheses, return statements, and semicolons at the end of statements. ■Note The rules that govern optional parentheses are unambiguous, but it’s generally good style to include parentheses in all but the simplest of cases (for example, in a println statement). APPENDIX ■ THE GROOVY LANGUAGE 547 In addition, some import statements are optional, because Groovy automatically imports the following packages for you: • groovy.lang.* • groovy.util.* • java.lang.* • java.util.* • java.util.regex.* • java.net.* • java.io.* • java.math.BigDecimal, java.math.BigInteger Besides these differences, Groovy’s main goal is to add features that make the common tasks faced by Java developers trivial. To facilitate this, Groovy supports the following: • Closures (similar to anonymous code blocks but with different scoping rules) • Advanced String support with interpolation (described in the “Groovy Strings” section of this chapter), regular expressions, and template generation • True object oriented programming with autoboxing/unboxing • Operator overloading and syntactic structures to ease access to existing Java classes • Improved syntax for existing data types augmented by new types • An extended library of methods onto existing Java classes At this point, we’ve tackled many of the similarities and differences with Java but have yet to show any actual code. In the next section, you’ll start your journey into Groovy by getting the basics right first. The Basics The Groovy syntax is extremely closely aligned to that of Java; this does not mean you can copy and paste Java code into Groovy, and vice versa (although in some cases this does work), but it does mean that it all feels very familiar. Fundamentally, Groovy can be written either in classes or as a script. Implementing the “Hello World!” example as a Groovy script would involve one line of code: println 'Hello World!' Assuming you’ve saved this code in a file called Hello.groovy, executing it is trivial too: groovy Hello.groovy 548 APPENDIX ■ THE GROOVY LANGUAGE Groovy automatically creates an executable class from the script. The reason this is high- lighted is that it is important to note that even though no class has been declared, the previous code will inevitably still become a class that extends groovy.lang.Script. ■Note The groovy.lang.Script class is the superclass used by Groovy to provide support for running arbitrary snippets of code as scripts. Like Java, everything in Groovy must be a class. Declaring Classes Class declaration is simple and familiar enough. Listing A-1 shows an example of a simple HelloController class from a Grails application. Listing A-1. HelloController.groovy class HelloController { def world = { render "Hello World it's " + new java.util.Date() } } Here we have defined a class called HelloController that contains a single property called world. The property itself has been assigned a value, which is a closure. Java developers may be a little confused at the moment as how this simple declaration can be a property given the ver- bosity of the property syntax in Java. Essentially, another difference from Java is that Groovy has no concept of the default visibility (also known as package-level visibility). Instead, properties declared at the default level, without any explicit modifiers such as private, protected, or public, are assumed to be JavaBean properties, and the appropriate getters and setters are generated for you. The lack of default visibility also becomes clear when defining methods, because methods are assumed to be public if no modifier is specified. In the next few sections, we’ll cover some of these, as well as some of the other powerful features that Groovy offers, starting with built-in assertions. Language-Level Assertions Assertions are a concept introduced to the Java language in JDK 1.4 that allow you to verify application state at a certain point. Like Java, Groovy has an assert keyword. APPENDIX ■ THE GROOVY LANGUAGE 549 Assertions are primarily useful to avoid the scenario where code is executed under an invalid state and, to this end, are a useful debugging tool. In terms of this book, assertions are also useful for revealing what the current state of an executing Groovy program is. Listing A-2 shows an example of an assertion in action. Listing A-2. Groovy Assertions def num = 1 … assert num == 1 Here we simply verify that the variable called num still has a value of 1 at the point of exe- cution in the code. Assertions will be utilized throughout many of the following examples, including in our coverage of Groovy strings, which we’ll cover next. Groovy Strings Groovy supports a concept found in many other languages such as Perl and Ruby called string interpolation. Because this is rather a mouthful in Groovy-land, they’re simply (or comically, depending on which way you look at it) known as GStrings. A GString is just like a normal string, but it allows the embedding of variables within it, using the familiar ${..} syntax found in many popular Java frameworks including Spring, Ant, and an array of view technologies. The curly braces can be omitted if it is simply the variable name that is required. Listing A-3 also demonstrates another powerful feature of Groovy’s string support: multiline strings. These are defined with the triple-quotation syntax. Listing A-3. GStrings in Action def person = "John" println """ ${new Date()} Dear $person, This is a Groovy letter! Yours Sincerely, The XYZ Company """ 550 APPENDIX ■ THE GROOVY LANGUAGE On the first line of the listing, a variable called person is defined that is then later refer- enced from the String itself. The multiline String can span several lines and includes all new line characters, tabs, and spaces in its output.