Programming Groovy Dynamic Productivity for the Java Developer 1st Edition Venkat Subramaniam All Chapters Instant Download
Programming Groovy Dynamic Productivity for the Java Developer 1st Edition Venkat Subramaniam All Chapters Instant Download
com
https://ebookname.com/product/programming-groovy-dynamic-
productivity-for-the-java-developer-1st-edition-venkat-
subramaniam/
OR CLICK BUTTON
DOWLOAD EBOOK
https://ebookname.com/product/programming-groovy-2-dynamic-
productivity-for-the-java-developer-2nd-edition-venkat-subramaniam/
ebookname.com
https://ebookname.com/product/programming-scala-tackle-multi-core-
complexity-on-the-java-virtual-machine-1st-edition-venkat-subramaniam/
ebookname.com
https://ebookname.com/product/programming-concurrency-on-the-jvm-
mastering-synchronization-stm-and-actors-venkat-subramaniam/
ebookname.com
https://ebookname.com/product/petrology-of-sedimentary-rocks-second-
edition-sam-boggs-jr/
ebookname.com
Dark Secrets of the Old Oak Tree Southern Tree Series
First Edition Dolores J. Wilson
https://ebookname.com/product/dark-secrets-of-the-old-oak-tree-
southern-tree-series-first-edition-dolores-j-wilson/
ebookname.com
https://ebookname.com/product/mysql-and-java-developer-s-guide-1st-
edition-mark-matthews/
ebookname.com
https://ebookname.com/product/international-review-of-research-in-
developmental-disabilities-1st-edition-hodapp/
ebookname.com
https://ebookname.com/product/stand-and-deliver-high-impact-
presentation-4th-edition-speech/
ebookname.com
An Introduction to Qualitative Research Becoming
Culturally Responsive 1st Edition Maria K E Lahman
https://ebookname.com/product/an-introduction-to-qualitative-research-
becoming-culturally-responsive-1st-edition-maria-k-e-lahman/
ebookname.com
What readers are saying about Programming Groovy
Venkat Subramaniam
Every precaution was taken in the preparation of this book. However, the publisher
assumes no responsibility for errors or omissions, or for damages that may result from
the use of information (including program listings) contained herein.
Our Pragmatic courses, workshops, and other products can help you and your team
create better software and have more fun. For more information, as well as the latest
Pragmatic titles, please visit us at
http://www.pragprog.com
ISBN-10: 1-934356-09-3
ISBN-13: 978-1-934356-09-8
Printed on acid-free paper with 50% recycled, 15% post-consumer content.
–
1 Introduction 16
1.1 Why Dynamic Languages? . . . . . . . . . . . . . . . . . 16
1.2 What’s Groovy? . . . . . . . . . . . . . . . . . . . . . . . 19
1.3 Why Groovy? . . . . . . . . . . . . . . . . . . . . . . . . . 20
1.4 What’s in This Book? . . . . . . . . . . . . . . . . . . . . 23
1.5 Who Is This Book For? . . . . . . . . . . . . . . . . . . . 26
1.6 Acknowledgments . . . . . . . . . . . . . . . . . . . . . . 26
I Beginning Groovy 29
2 Getting Started 30
2.1 Getting Groovy . . . . . . . . . . . . . . . . . . . . . . . . 30
2.2 Installing Groovy . . . . . . . . . . . . . . . . . . . . . . 31
2.3 Test-Drive Using groovysh . . . . . . . . . . . . . . . . . 32
2.4 Using groovyConsole . . . . . . . . . . . . . . . . . . . . 33
2.5 Running Groovy on the Command Line . . . . . . . . . 34
2.6 Using an IDE . . . . . . . . . . . . . . . . . . . . . . . . . 35
4 Dynamic Typing 75
4.1 Typing in Java . . . . . . . . . . . . . . . . . . . . . . . . 75
4.2 Dynamic Typing . . . . . . . . . . . . . . . . . . . . . . . 78
4.3 Dynamic Typing != Weak Typing . . . . . . . . . . . . . 79
4.4 Design by Capability . . . . . . . . . . . . . . . . . . . . 80
4.5 Optional Typing . . . . . . . . . . . . . . . . . . . . . . . 86
4.6 Types in Groovy . . . . . . . . . . . . . . . . . . . . . . . 86
4.7 Multimethods . . . . . . . . . . . . . . . . . . . . . . . . 87
4.8 Dynamic: To Be or Not to Be? . . . . . . . . . . . . . . . 91
5 Using Closures 92
5.1 Closures . . . . . . . . . . . . . . . . . . . . . . . . . . . 92
5.2 Use of Closures . . . . . . . . . . . . . . . . . . . . . . . 96
5.3 Working with Closures . . . . . . . . . . . . . . . . . . . 98
5.4 Closure and Resource Cleanup . . . . . . . . . . . . . . 98
5.5 Closures and Coroutines . . . . . . . . . . . . . . . . . . 101
5.6 Curried Closure . . . . . . . . . . . . . . . . . . . . . . . 102
5.7 Dynamic Closures . . . . . . . . . . . . . . . . . . . . . . 105
5.8 Closure Delegation . . . . . . . . . . . . . . . . . . . . . 107
5.9 Using Closures . . . . . . . . . . . . . . . . . . . . . . . 110
15 MOPping Up 224
15.1 Creating Dynamic Classes with Expando . . . . . . . . 224
15.2 Method Delegation: Putting It All Together . . . . . . . 227
15.3 Review of MOP Techniques . . . . . . . . . . . . . . . . . 231
B Bibliography 296
Index 298
Foreword
Back in 2003, when we started Groovy, our goal was to provide Java
developers with an additional language to complement Java, a new
Swiss Army knife to add to their tool belt. Java is a great language and
a wonderful platform, but sometimes you need the agility and expres-
siveness of scripting languages or, even better, dynamic languages. We
didn’t want a new language that would be a paradigm shift for Java
developers. Instead, Groovy was made to seamlessly integrate with Java
in all possible ways while at the same time adding all the goodies
you would expect from a dynamic language. The best of both worlds!
You don’t even have to wait for Java 7, 8, or 9 to get all the nuggets
you’d want to have in your next programming language of choice: clo-
sures, properties, native syntax for lists, maps, and regular expres-
sions. Everything is already there.
Over the course of time, Groovy has matured a lot and has become a
very successful open source dynamic language used by tons of Java
developers and by big companies that embed it in their applications
servers or their mission-critical applications. Groovy lets you write more
expressive unit tests and simplifies XML parsing or SQL data imports,
and for your mundane tasks, there’s a scripting solution perfectly inte-
grated with your Java ecosystem. When you need to extend your appli-
cation to customize it to your needs, you can also integrate Groovy
at specific points by injecting Groovy scripts. Thanks to Groovy’s mal-
leable syntax, you can even create domain-specific languages fairly eas-
ily to represent business rules that even end users can author.
Now, step back a little. At first sight, despite the marketing taint of
the previous paragraphs, it sounds great, and you probably see a few
places where you’d definitely need to use such a versatile tool. But it’s
just something else you have to learn to be able to leverage it to its
fullest extent, right? You’re a Java developer, so do you fear it’s going
to be difficult to get the best out of it without wasting too much of your
time and energy?
F OREWORD 15
Fortunately, this book is right for you. Venkat will guide you through
Groovy and its marvels. Without being a boring encyclopedia, this book
covers a lot of ground. And in a matter of hours (well, in fact, just the
time to read the book), you’ll be up to speed, and you’ll see how Groovy
was made by Java developers for Java developers. You won’t regret your
journey, and you’ll be able to keep this book on your desk for reference
or for finding new creative ways to solve the problem of the day.
Introduction
As a busy Java developer, you’re constantly looking for ways to be more
productive, right? You’re probably willing to take all the help you can
get from the platform and tools available to you. When I wax poetic
about the “strength of Java,” I’m not talking about the language or its
syntax. It’s the Java platform that has become more capable and more
performant. To reap the benefit of the platform and to tackle the inher-
ent complexities of your applications, you need another tool—one with a
dynamic and metaprogramming capabilities. Java—the language—has
been flirting with that idea for a while and will support these features
to various degrees in future versions. However, you don’t have to wait
for that day. You can build performant Java applications with all the
dynamic capabilities today, right now, using Groovy.
1. Tim O’Reilly observes the following about developing web applications: “Rather than
being finished paintings, they are sketches, continually being redrawn in response to
new data.” He also makes the point that dynamic languages are better suited for these in
“Why Scripting Languages Matter” (see Appendix A, on page 291).
2. A fifth reason is the ability to run dynamic languages on the JVM, but that came
much later.
W HY D YNAMIC L ANGUAGES ? 18
3. The Groovy users mailing list is very active, with constant discussions from passion-
ate users expressing opinions, ideas, and criticisms on current and future features. Visit
http://groovy.codehaus.org/Mailing+Lists and http://groovy.markmail.org if you don’t believe me.
4. “Legacy code is simply code without tests.” —Michael C. Feathers [Fea04]
W HAT ’ S G ROOVY ? 19
on. In this section, I will discuss whether Groovy is the right language
for you.
As a programmer, I am shameless about languages. I can comfortably
program in about eight structured, object-oriented, and functional pro-
gramming languages and can come dangerously close to writing code
in a couple more. In any given year, I actively code in about two to three
languages at least. So, if one thing, I am pretty unbiased when it comes
to choosing a language—I will pick the one that works the best for a
given situation. I am ready to change to another language with the ease
of changing a shirt, if that is the right thing to do, that is.
Groovy is an attractive language for a number of reasons:
• It has a flat learning curve.
• It follows Java semantics.
• It bestows dynamic love.
• It extends the JDK.
I’ll now expand on these reasons. First, you can take almost any Java
code9 and run it as Groovy. The significant advantage of this is a flat
learning curve. You can start writing code in Groovy and, if you’re
stuck, simply switch gears and write the Java code you’re familiar with.
You can later refactor that code and make it groovier.
For example, Groovy understands the traditional for loop. So, you can
write this:
// Java Style
for(int i = 0; i < 10; i++)
{
//...
}
As you learn Groovy, you can change that to the following code or one
of the other flavors for looping in Groovy (don’t worry about the syntax
right now; after all, you’re just getting started, and very soon you’ll be
a pro at it):
10.times {
//...
}
println XmlParser.class
println XmlParser.class.superclass
Now let’s talk about the third reason to love Groovy. Groovy is dynamic,
and it is optionally typed. If you’ve enjoyed the benefits of other dynamic
languages such as Smalltalk, Python, JavaScript, and Ruby, you can
realize those in Groovy. If you had looked at Groovy 1.0 support for
metaprogramming, it probably left you desiring for more. Groovy has
come a long way since 1.0, and Groovy 1.5 has pretty decent metapro-
gramming capabilities.
For instance, if you want to add the method isPalindrome( ) to String—a
method that tells whether a word spells the same forward and back-
ward—you can add that easily with only a couple lines of code (again,
don’t try to figure out all the details of how this works right now; you
have the rest of the book for that):
Download Introduction/Palindrome.groovy
String.metaClass.isPalindrome = {->
delegate == delegate.reverse()
}
word = 'tattarrattat'
println "$word is a palindrome? ${word.isPalindrome()}"
word = 'Groovy'
println "$word is a palindrome? ${word.isPalindrome()}"
Finally, as a Java programmer, you rely heavily on the JDK and the API
to get your work done. These are still available in Groovy. In addition,
W HAT ’ S IN T HIS B OOK ? 23
Groovy extends the JDK with convenience methods and closure support
through the GDK. Here’s a quick example of an extension in GDK to the
java.util.ArrayList class:
lst = ['Groovy' , 'is' , 'hip' ]
println lst.join(' ' )
println lst.getClass()
The output from the previous code confirms that you’re still working
with the JDK but that you used the Groovy-added join( ) method to con-
catenate the elements in the ArrayList:
Groovy is hip
class java.util.ArrayList
You can see how Groovy takes the Java you know and augments it.
If your project team is familiar with Java, if they’re using it for most
of your organization’s projects, and if you have a lot of Java code to
integrate and work with, then you will find that Groovy is a nice path
toward productivity gains.
working with multiple Java/Groovy classes and scripts—so you can put
Groovy to use right away for your day-to-day tasks. I also discuss the
Groovy extensions and additions to the JDK so you can take advantage
of both the power of Groovy and the JDK at the same time.
In the chapters in Part 3, “MOPping Groovy,” I focus on the metapro-
gramming capabilities of Groovy. You’ll see Groovy really shine in these
chapters and learn how to take advantage of its dynamic nature. You’ll
start with the fundamentals of MetaObject Protocol (MOP), learn how to
do aspect-oriented programming (AOP) such as operations in Groovy,
and learn about dynamic method/property discovery and dispatching.
Then you’ll apply those right away to creating and using builders and
domain-specific languages (DSLs). Unit testing is not only necessary in
Groovy because of its dynamic nature, but it is also easier to do—you
can use Groovy to unit test your Java and Groovy code, as you’ll see in
this part of the book.
Here’s what’s in each chapter:
Part 1: “Beginning Groovy”
In Chapter 2, Getting Started, on page 30, you’ll download and install
Groovy and take it for a test-drive right away using groovysh and groovy-
Console. You’ll also learn how to run Groovy without these tools—from
the command line and within your IDEs.
In Chapter 3, Groovy for the Java Eyes, on page 37, you’ll start with
familiar Java code and refactor that to Groovy. After a quick tour of
Groovy features that improve your everyday Java coding, you’ll learn
about Groovy’s support for Java 5 features. Groovy follows Java seman-
tics, except in places it does not—you’ll also learn gotchas that’ll help
avoid surprises.
In Chapter 4, Dynamic Typing, on page 75, you’ll see how Groovy’s
typing is similar and different from Java’s typing, what Groovy really
does with the type information you provide, and when to take advan-
tage of dynamic typing vs. optional typing. You’ll also learn how to take
advantage of Groovy’s dynamic typing, design by capability, and multi-
methods.
In Chapter 5, Using Closures, on page 92, you’ll learn all about the
exciting Groovy feature called closures, including what they are, how
they work, and when and how to use them.
W HAT ’ S IN T HIS B OOK ? 25
EDUCATION: A. D. 1785-1880.
The United States.-
Land-grants for Schools.
"The question of the endowment of educational institutions by
the Government in aid of the cause of education seems to have
met no serious opposition in the Congress of the
Confederation, and no member raised his voice against this
vital and essential provision relating to it in the ordinance
of May 20, 1785, 'for ascertaining the mode of disposing of
lands in the Western Territory.' This provided: 'There shall
be reserved the lot No. 16 of every township for the
maintenance of public schools within said township.' This was
an endowment of 640 acres of land (one section of land, one
mile square) in a township 6 miles square, for the support and
maintenance of public schools' within said township.' The
manner of establishment of public schools thereunder, or by
whom, was not mentioned. It was a reservation by the United
States, and advanced and established a principle which finally
dedicated one thirty-sixth part of all public lands of the
United States, with certain exceptions as to mineral, &c., to
the cause of education by public schools. ... In the
Continental Congress, July 13, 1787, according to order, the
ordinance for the government of the 'Territory of the United
States northwest of the river Ohio' came on, was read a third
time, and passed [see NORTHWEST TERRITORY: A. D.1787]. It
contained the following: 'Art. 3. Religion, morality, and
knowledge being necessary to good government and the happiness
of mankind, schools and the means of education shall forever
be encouraged.' The provision of the ordinance of May 20,
1785, relating to the reservation of the sixteenth section in
every township of public land, was the inception of the
present rule of reservation of certain sections of land for
school purposes. The endowment was the subject of much
legislation in the years following. The question was raised
that there was no reason why the United States should not
organize, control, and manage these public schools so endowed.
The reservations of lands were made by surveyors and duly
returned. This policy at once met with enthusiastic approval
from the public, and was tacitly incorporated into the
American system as one of its fundamental organic ideas.
Whether the public schools thus endowed by the United States
were to be under national or State control remained a
question, and the lands were held in reservation merely until
after the admission of the State of Ohio in 1802. ... To each
organized Territory, after 1803, was and now is reserved the
sixteenth section (until after the Oregon Territory act
reserved the thirty-sixth as well) for school purposes, which
reservation is carried into grant and confirmation by the
terms of the act of admission of the Territory or State into
the Union; the State then becoming a trustee for school
purposes. These grants of land were made from the public
domain, and to States only which were known as public-land
States. Twelve States, from March 3, 1803, known as
public-land States, received the allowance of the sixteenth
section to August 14, 1848. ... Congress, June 13, 1812, and
May 26, 1824, by the acts ordering the survey of certain towns
and villages in Missouri, reserved for the support of schools
in the towns and villages named, provided that the whole
amount reserved should not exceed one-twentieth part of the
whole lands included in the general survey of such town or
village. These lots were reserved and sold for the benefit of
the schools. Saint Louis received a large fund from this
source. ... In the act for the organization of the Territory
of Oregon, August 14, 1848, Senator Stephen A. Douglas
inserted an additional grant for school purposes of the
thirty-sixth section in each township, with indemnity for all
public-land States thereafter to be admitted, making the
reservation for school purposes the sixteenth and thirty-sixth
sections, or 1,280 acres in each township of six miles square
reserved in public-land States and Territories, and confirmed
by grant in terms in the act of admission of such State or
Territory into the Union. From March 13, 1853, to June 30,
1880, seven States have been admitted into the Union having a
grant of the sixteenth and thirty-sixth sections, and the
same area has been reserved in eight Territories."
T. Donaldson, The Public Domain, chapter 13.
{732}
EDUCATION: A. D. 1789.
The United States.
EDUCATION: A. D. 1793.-Massachusetts.
Williams College.
EDUCATION: A. D. 1795-1867.
The United States.
State School Funds.
EDUCATION: A. D. 1804-1837.
Michigan.
The University.
ALSO IN:
E. M. Farrand, History of the University of Michigan.
EDUCATION: A. D. 1818-1821.
Massachusetts.
Amherst College.
EDUCATION: A. D. 1837.
Massachusetts.
Horace Mann and the State System.
EDUCATION: A. D. 1840-1886.
The United States.
Proportion of College Students.
{734}
EDUCATION: A. D. 1844-1876.
Canada.
Ontario School System.
EDUCATION: A. D. 1862.
The United States.
Land-grant for industrial Colleges.
{735}
EDUCATION: A. D. 1862-1886.
New York.
Cornell University.
EDUCATION: A. D. 1866-1869.
The United States.
Bureau of Education.
EDUCATION: A. D. 1867.
New York.
Public Schools made entirely free.
The public schools of the State of New York were not entirely
free until 1867. In his report to the Legislature made in
February of that year, the State Superintendent of Public
Instruction, Honorable Victor M. Rice, said: "The greatest defect
in our school system is, as I have urged in previous reports,
the continuance of the rate bill system. Our common schools
can never reach their highest degree of usefulness until they
shall have been made entirely free. ... To meet this public
demand, to confer upon the children of the State the blessings
of free education, a bill has already been introduced into
your honorable body. ... The main features of the bill are the
provisions to raise, by State tax, a sum about equal to that
raised in the districts by rate bills, and to abolish the rate
bill system; to facilitate the erection and repair of school
houses." The bill referred to was passed at the same session
of the Legislature, and in his next succeeding report,
Superintendent Rice gave the following account of the law and
its immediate effects: "While the general structure of the
school law was not disturbed, a material modification was made
by the Act (chap. 406, Laws of 1867), which took effect on the
first day of October of the same year, and which, among other
things, provided for the abolishment of rate-bills, and for
increased local and State taxation for school purposes. This
was primarily a change in the manner of raising the requisite
funds; not an absolute increase of the aggregate amount to be
raised. It involved and encouraged such increase, so far as
the inhabitants in the several school districts should
authorize it, by substituting taxation exclusively on
property, for a mixed assessment which, in part, was a tax on
attendance. Thus relieved of an old impediment, and supplied
with additional power and larger resources, the cause of
public instruction, during the last fiscal year, has wrought
results unequaled in all the past. ... The effect of this
amendment has not been confined to the financial policy
thereby inaugurated. It is distinctly traceable in lengthened
terms of school, in a larger and more uniform attendance, and
in more liberal expenditures for school buildings and
appliances."
EDUCATION: A. D. 1867.
Maryland.
Johns Hopkins University.
EDUCATION: A. D. 1867-1891.
The United States.
The Peabody Education Fund.
EDUCATION: A. D. 1884-1891.
California.
Leland Stanford Junior University.
{738}
EDUCATION: A. D. 1887-1889.
Massachusetts.
Clark University.
EDUCATION: A. D. 1889-1892.
Illinois.
Chicago University.
"At its Annual Meeting in May, 1889, the Board of the American
Baptist Education Society resolved to take immediate steps
toward the founding of a well-equipped college in the city of
Chicago. At the same time John D. Rockefeller made a
subscription of $600,000 and this sum was increased during the
succeeding year by about $600,000 more in subscriptions
representing more than two thousand persons. Three months
after the completion of this subscription, Mr. Rockefeller
made an additional proffer of $1,000,000. The site of the
University consists of three blocks of ground--about two
thousand feet long and three hundred and sixty-two feet wide,
lying between the two South Parks of Chicago, and fronting on
the Midway Plaisance, which is itself a park connecting the
other two. One-half of this site is a gift of Marshall Field
of Chicago, and the other half has been purchased at a cost of
$132,500. At the first meeting of the Board after it had
become an incorporated body, Professor William R. Harper, of
Yale University, was unanimously elected President of the
University. ... It has been decided that the University will
begin the work of instruction on the first day of October,
1892. ... The work of the University shall be arranged under
three general divisions, viz., The University Proper, The
University-Extension Work, The University Publication Work."
University of Chicago,
Official Bulletin no. 1, January, 1891.
EDUCATION: A. D. 1890.
United States.
Census Statistics.
EDUCATION: A. D. 1638-1671.
Comenius.
Our website is not just a platform for buying books, but a bridge
connecting readers to the timeless values of culture and wisdom. With
an elegant, user-friendly interface and an intelligent search system,
we are committed to providing a quick and convenient shopping
experience. Additionally, our special promotions and home delivery
services ensure that you save time and fully enjoy the joy of reading.
ebookname.com