Groovy in Action, Second Edition

Groovy in Action, Second Edition free pdf ebook was written by Dierk König on March 18, 2011 consist of 33 page(s). The pdf file is provided by www.manning.com and available on pdfpedia since April 21, 2012.

meap edition manning early access program copyright 2011 manning..post comments or corrections to the author online forum: http://www.manning-sandbox.com/forum.jspa?forumid=571 2 1 your way..can expect even more from learning groovy. groovy will give you...

x
send send what is readshare?


Thank you for helping us grow by simply clicking on facebook like and google +1 button below ^^

Groovy in Action, Second Edition pdf




Read
: 7295
Download
: 743
Uploaded
: April 21, 2012
Category
Author
: Dierk König
Total Page(s)
: 33
Groovy in Action, Second Edition - page 1
 
You're reading the first 10 out of 33 pages of this docs, please download or login to readmore.
Groovy in Action, Second Edition - page 2
MEAP Edition Manning Early Access Program Copyright 2011 Manning Publications For more information on this and other Manning titles go to www.manning.com ©Manning Publications Co. Please post comments or corrections to the Author Online forum: http://www.manning-sandbox.com/forum.jspa?forumID=571
Groovy in Action, Second Edition - page 3
Table of Contents Part I: The Groovy language 1 Your way to Groovy 2 Overture: The Groovy basics 3 The simple Groovy datatypes 4 The collective Groovy datatypes 5 Working with closures 6 Groovy control structures 7 Object orientation, Groovy style 8 Dynamic programming with Groovy 9 Compile-time meta programming and AST Transformations Part II: Around the Groovy library 10 Working with builders 11 Working with the GDK 12 Database programming with Groovy 13 Integrating Groovy 14 Working with XML Part III: Everyday Groovy 15 Tips and tricks 16 Unit testing with Groovy 17 Concurrent Groovy with GPars 18 Domain Specific Languages (DSLs) 19 Groovy modules and frameworks 20 Groovy best practice patterns ©Manning Publications Co. Please post comments or corrections to the Author Online forum: http://www.manning-sandbox.com/forum.jspa?forumID=571
Groovy in Action, Second Edition - page 4
2 Your way to Groovy 1 A smooth introduction to Groovy What Groovy is all about How it makes your programming life easier How to start Seek simplicity, and distrust it. -- Alfred North Whitehead You've heard of Groovy, maybe even installed the distribution and tried some snippets from the online tutorials. Perhaps your project has adopted Groovy as a dynamic extension to Java and you now seek information about what you can do with it. You may have been acquainted with Groovy from using the Grails web application platform, the Griffon desktop application framework, the Gradle build system or the the Spock testing facility and now look for background information about the language that these tools are built upon. This book delivers to that purpose but you can expect even more from learning Groovy. 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 a pleasure to use. Learning Groovy is a wise investment. Groovy brings the power of advanced language features such as closures, dynamic methods, and the meta object protocol
Groovy in Action, Second Edition - page 5
3 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. Groovy follows a pragmatic “no drama” 1 approach: it obeys the Java object model and always keeps the perspective of a Java programmer. It doesn't force you into any new programming paradigm but offers you those advanced capabilities that you legitimately expect from a “top of stack” language. Footnote 1 m thanks to Mac Liaw for this wording This first chapter 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 chapter, 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 book for guidance and reference. 1.1 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. He and his wife were waiting for a late plane. While she went shopping, he visited an Internet cafe 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.
Groovy in Action, Second Edition - page 6
4 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.1 shows how this unique combination defines Groovy's position in the varied world of languages for the Java platform. 2 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. Footnote 2 m http://www.robert-tolksdorf.de/vmlanguages.html lists about 240 (!) languages targeting the Java Virtual Machine. Figure 1.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. In the early days of Groovy, we were mainly asked how it would compare to Java, Beanshell, Pnuts, and embedded expression languages. The focus was clearly on Java-friendliness. Then the focus shifted to dynamic capabilities and the debate went on putting Groovy, JavaScript (Rhino), Jython, and JRuby side by side. Since recently, we see more comparison with JavaFX, Clojure, Scala, Fan, Nice, Newspeak and Jaskell. Most of them introduce the functional programming paradigm to the Java platform, which makes a comparison on the feature dimension rather difficult. They are simply different. Some other JVM languages like Alice and Fortress are even totally unrelated. By the time you read this, some new kids are likely to have appeared on the block and the pendulum may have swung in a totally different direction. But with the landscape picture above you are able to also position upcoming languages. Some languages may offer more advanced features than Groovy. Not so many
Groovy in Action, Second Edition - page 7
5 languages may claim to fit equally well to the Java language. None can currently touch Groovy when you consider both aspects together: Nothing provides a better combination of Java friendliness and a complete feature set. With Groovy being in this position, what are its main characteristics, then? 1.1.1 What is Groovy? Groovy is an optionally typed, 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. Unlike other alternative languages, it is designed as a companion, not a replacement for Java. 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, 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 book, 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 wasn't designed for. Let's take a closer look at what makes Groovy so appealing, starting with how Groovy and Java work hand-in-hand.
Groovy in Action, Second Edition - page 8
6 1.1.2 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. SEAMLESS INTEGRATION Figure 1.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 1.2 Groovy and Java join together in a tongue-and-groove fashion. Consequently, calling Java from Groovy is a nonissue. 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 . You can call all methods on it that you know are available for a Date and you can pass it as an argument to any method that expects a Date. Calling into Java is an easy exercise. It is something that all JVM languages offer--at least the ones worth speaking of. They all make it possible, some by staying inside their own non-Java abstractions, some by providing a gateway. Groovy is one of the few that does it its own way and the Java way at the same time, since there is no difference. Integration in the opposite direction is just as easy. Suppose a Groovy class MyGroovyClass is compiled into MyGroovyClass.class and put on the classpath. You can use this Groovy class from within a Java class by typing new MyGroovyClass(); // create from Java 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 in Action, Second Edition - page 9
7 Groovy. This becomes particularly important when integrating with Java frameworks that call your class where you have no control over how that call is effected. The “interoperability” in this direction is a bit more involved for alternative JVM languages. Yes, they may “compile to bytecode” but that does not mean much for itself, since one can produce valid bytecode that is totally incomprehensible for a Java caller. A language may not even be object-oriented and provide classes and methods. And even if it does, it may assign totally different semantics to those abstractions. Groovy in contrast fully stays inside the Java object model. Actually, compiling to class files is only one of many ways to integrate Groovy into your Java project. The integration chapter describes the full range of options. The integration ladder in figure 1.3 arranges the integration criteria by their significance. Figure 1.3 The integration ladder shows increasing cross-language support from simple calls for interoperability up to seamless tool integration. One step up on the integration ladder and we meet the issue of references. A Groovy class may reference a Java class (that goes without saying) and a Java class may reference a Groovy class, as we have seen above. We can even have circular references and groovyc compiles them all transparently. Even better, the leading IDEs provide cross-language compile, navigation, and refactoring such that you
Groovy in Action, Second Edition - page 10
8 hardly ever need to care about the project build setup. You are free to choose Java or Groovy when implementing any class for that matter. Such a tight build-time integration is a challenge for every other language. Overloaded methods is the next rung where candidates slip off. Imagine you set out to implement the Java interface java.io.Writer in any non-Java language. It comes with three versions of “write” that take one parameter: write(int c), write(String str) , and write(char[] buf) . Implementing this in Groovy is trivial, it's exactly like in Java. The formal parameter types distinguish which methods you override. That's one of many merits of optional typing. Languages that are solely dynamically typed have no way of doing this. But the buck doesn't stop here. The Java/Groovy mix allows annotations and interfaces being defined in either language and implemented and used in the other. You can subclass in any combination even with abstract classes and “sandwich” inheritance like Java - Groovy - Java or Groovy - Java - Groovy in arbitrary depth. It may look exotic at first sight but we actually needed this feature in customer projects. We'll come back to that. Of course, this integration presupposes that your language knows about annotations and interfaces like Groovy does. True seamless integration means that you can take any Java class from a given Java codebase and replace it with a Groovy class. Likewise, you can take any Groovy class and rewrite it in Java both without touching any other class in the codebase. That's what we call a drop-in replacement , which imposes further consideration about annotations, static members, and accessibility of the used libraries from Java. Finally, generated bytecode can be more or less Java-tool-friendly. There are more and more tools on the market that directly augment your bytecode, be it for gathering test coverage information or “weaving aspects” in. These tools do not only expect bytecode to be valid but also to find well-known patterns in it such as the Java and Groovy compiler provide. Bytecode generated by other languages is often not digestable for such tools. Alternative JVM languages are often attributed as working “seamlessly” with Java. With the integration ladder above, you can check to what degree this applies: calls into Java, calls from Java, bidirectional compilation, inheritance intermix, mutual class substitutability, and tool support. We didn't even consider security, profiling, debugging and other Java “architectures”. So much for the platform integration, now onto the syntax.
You're reading the first 10 out of 33 pages of this docs, please download or login to readmore.

People are reading about...