The following simple Groovy script demonstrates use of Groovy's static import. One case prints out the value of Math.PI using both traditional Java regular import support and traditional Java static import support. The other examples are all Groovy and demonstrate how Groovy's static import even allows method calls to be referenced by constants defined with a Groovy static import. I attempted to place enough comments in this script to help show off Groovy's various static import features.

The output from running the above script is shown in the next screen snapshot.

Conclusion

Not everyone is a fan of Java's static import, but I think they it does have its time and place (the documentation states to use it very sparingly). Groovy's feature-rich static imports can make for more readable scripts when used appropriately.

The quotation "There have always been ghosts in the machine" from 2004's I, Robot articulates what just about every computer user or developer has thought at least once. Race conditions, memory leaks, and other non-obvious problems can lead users to believe that there are indeed ghosts or gremlins in the machine. And, if you listen to or read Dr. Alfred Lanning's quotation further, it is even easier to find more connections: "Random segments of code, that have grouped together to form unexpected protocols." This is a reminder of why code coverage and thorough testing are so important!

2. This can't be good.

This quote ("This can't be good.") was one I used even before seeing and hearing Sam Flynn state it in Tron: Legacy (2010). This is an apropos response to running into telltale symptoms of nasty issues like file system problems, network issues, deadlocks, memory leaks, race conditions, and the other stuff that we've all seen before. Even our own misbehaving software may lead us to say this.

3. Never theorize before you have data.

This Sherlock Holmes statement to Dr. John Watson from 2009's Sherlock Holmes fits nicely in the software development world. It is tempting at times, almost beyond what we can resist, to jump to conclusions and "solve the problem" before adequately assessing what the real culprit is. The problem is, as Mr. Holmes suggests, that we will "end up twisting facts to suit theories, instead of theories to suit facts" if we theorize too quickly. Effective debugging techniques, disciplined unit testing, and reproducing the problem before "solving it" are obvious tactics we can use to deal with this correctly as Sherlock Holmes recommends.

4. We mock what we don't understand.

This Austin Millbarge quote from 1985's Spies Like Us has proven handy when on the receiving end of criticism (productive and constructive or not) in situations like design reviews, code reviews, and various other forums. The tone of voice can be the difference between humorous acknowledgement that the cited issue is valid and should be addressed or the more literal interpretation that the criticizer doesn't understand what he or she is talking about.

5. You know, somehow, 'I told you so' just doesn't quite say it.

It is difficult to not say something along the lines of this Detective Del Spooner quote when our own advice or opinion has been proven out by events after being overridden by management or peers. Our situations may not be as dire as robots taking over, but this I, Robot quotation certainly fits in many situations we find ourselves in.

6. Stay on target!

"Stay on target!" may be one of the most oft-quoted lines of any movie within technology-oriented communities. It's short and easy to remember, it comes from one of the most popular tech-friendly movies of all time [1977's Star Wars IV: A New Hope], and it fits so many situations. I have used it to remind myself or colleagues to get back onto the main subject when a technical discussion or other activity has wandered off into the weeds or out of left field. "Stay on target" is a slightly humorous way to remind oneself or others to focus on the task at hand.

7. You rush a miracle man, you get rotten miracles.

I like this quote from 1987's The Princess Bride because it does so aptly fit software development. Even the best developers cannot deliver the same quality of solution when rushed too quickly. More mistakes are made and more complex issues are not thought out sufficiently when developers are too rushed. Some of the best developers may seem like miracle workers at times, but some of their products can be "rotten miracles" if they are rushed too much too often. An even more direct correspondence can be seen when steps of the software development (testing for example) are short-changed.

8. It would take a miracle.

Speaking of miracles and of The Princess Bride, Miracle Max has another great quote that can apply to software development. The more complete quote is an exchange with Valerie when she asks Miracle Max if he thinks the plan to storm the castle will work and Miracle Max replies, "It would take a miracle." This has been the same sentiment many of us have felt or even expressed when someone has suggested performing something analogous to storming a castle such trying to talk a decision-maker out of a poor decision with severe long-term consequences.

9. I wouldn't say I've been "missing" it.

In the movie Office Space (1999), Bob porter observes that colleague Peter Gibbons has not been in the office much lately: "Looks like you've been missing a lot of work lately." To this, Gibbons replies with the classic, "I wouldn't say I've been 'missing' it, Bob." I think most of us have felt this way at one time or another about a certain position, certain job, certain task, or certain activity. For example, I used this on a colleague (who happens to be a big fan of Office Space) recently when he said something along the lines of, "It looks like you missed our meeting." It was all too easy.

10. I love it when a plan comes together.

Popularized in virtually every episode of the original television series, this well-known quote from Col. John "Hannibal" Smith was highlighted in the 2010 movie The A-Team as well. The quote was usually stated after some crazy plan was hatched and after the good guys eventually won. Often in the television series, it was difficult to believe that what happened was the actual plan. This quote fits with many aspects of life and software development is no exception. When something finishes, whether according to plan or not, this is a statement bringing closure to the activity.

Conclusion

This third set of movie quotes summarizes the responses many of us probably feel (and possibly even state) when we run into certain software development situations, problems, and issues. Some of these quotes can be used to bring humor to stressful situations. The quotes work particularly well when the recipients are familiar with the quotes and their movie source and context.

The one-hour presentation "From Java SE, 2012, to Java 12: Java SE Roadmap" is to be presented by Oracle employees Adam Messinger, Peter Utzschneider, and Henrik Stahl. The title alone makes it obvious why this presentation is likely of great interest to Java developers.

Java EE 7 Overview and Oracle GlassFish Server Update (15597)

Oracle employees Adam Leftik and John Clingan plan to "cover the current status of Java EE 7, presenting an overview of new and updated specifications" and discuss how future GlassFish releases will provide these new features in their presentation "Java EE 7 Overview and Oracle GlassFish Server Update."

Diagnosing Scalability Issues in Java Applications on MySQL (15742)

This presentation, "Diagnosing Scalability Issues in Java Applications on MySQL," is by Oracle employees Todd Farmer and Mark Matthews. The abstract states that attendees will "learn how to diagnose and fix database- and application-level deadlocks and concurrency issues for Java applications deployed against MySQL."

Cloud-Enabled Java Persistence with Oracle TopLink (15615)

The abstract for "Cloud-Enabled Java Persistence with Oracle TopLink" states that the session will "examine the persistence requirements of Java applications in the cloud and introduces the features of Oracle TopLink that address them to simplify cloud application development." This presentation is by Shaun Smith and Doug Clarke, both of Oracle.

The developer Web profile is a key improvement in Java EE 6 servers, and Eclipse developers will want to work with it. This session demonstrates some aspects of the progress of Oracle WebLogic server on its road to Java EE 6 compliance and gives Eclipse developers a sneak peek at using Java Persistence API Release 2.0 and JavaServer Faces Release 2.0 with Oracle WebLogic's Web profile.

Production Java Diagnostics: Visibility Even Your Developer Does Not Have (14380)

The session "Production Java Diagnostics: Visibility Even Your Developer Does Not Have" by Oracle employees Neelima Bawa and Glen Hawkins "focuses on Oracle Enterprise Manager's ability to provide deep Java Virtual Machine diagnostics to quickly identify the root cause of problems within the JVM through heap stack and thread analysis as well as other detailed performance analytics based on real-time as well as historical details."

Speed Up XML Processing with Oracle XDK, XQJ, and XQuery (15714)

Oracle's Mark Drake is going to present "Speed Up XML Processing with Oracle XDK, XQJ, and XQuery." This session will demonstrate "how to build scalable XML processing systems with Oracle XML DB and Oracle XML Developer's Kit" and will provide "an introduction to using the XQuery API for Java (XQJ)." I have posted a few blog posts on XQuery previously.

Conclusion: JavaOne-less Oracle OpenWorld is not Java-less

I only listed a subset of the presentations at Oracle OpenWorld 2011 that are relevant to Java developers. When I use the keyword "Java" in the keyword search in the Oracle OpenWorld Content Catalog, there are 42 sessions returned as matches for that keyword.

In the post Compact Equals, Ezechukwu shows one implementation of a traditional equals method for the four String fields and single Integer field defined in the Compact Equals post. I have adapted the "traditional" approach very slightly here (mostly formatting):

This is very verbose and is a good example of the main reason I began switching from loathing the ternary operator to loving it. I was tired of these extremely verbose equals methods implementations and liked the implementations using the ternary operator much better. As I began writing more and more equals methods with ternaries, I became more comfortable with them. The next example is adapted from the Address class to use the ternary operators instead. In this case, I let NetBeans 7.0 do the work of generating the equals method because I knew that its automatic generation also employs the ternary operator for comparing field Strings. This implementation is shown in the next code listing.

The ternary operator makes the code less verbose, but Ezechukwu highlights another interesting approach in Compact Equals. His example populates arrays with the fields of each object being compared and then evaluates the equality of the two arrays using Arrays.equals(Object[], Object[]). An adapted version of this is shown in the next code listing.

It gets even better with the JDK 7-introduced Objects class. It is common wisdom that a consistent hashCode() method should be implemented whenever an equals(Object) method is overridden. In fact, NetBeans warns of this and its automatically generated hashCode() method looks like that shown next.

hashCode() Corresponding to Any of Above equals(Object) Implementations

I liked the Compact Equals post because it provided an interesting perspective on using Arrays.equals to compare two instances' fields and I also liked it because it provided me with a good starting point to work from to demonstrate the value of the JDK 7 Objects class in writing compact equals and hashCode implementations. The JDK 7 Objects class is going to change the way we write and maintain some of our most common methods in Java. It's a very welcome addition.

The next two screen snapshots demonstrate the traditional default appearance of Javadoc documentation we have seen for years and then demonstrate the new default appearance.

This default style is not limited to the standard SDK API documentation. It is also used for generating custom Javadoc for other Java applications. The next screen snapshot shows Javadoc being invoked via Ant using JDK 7 build 146 (the build supporting the new styling). The example built in this case is the code from my post How I Learned to Stop Worrying and Love Java's Ternary Operator.

As the screen snapshot indicates, I did not do anything special to apply the new styling. However, the output is new (and I think improved) as shown in the next couple snapshots.

The generated Javadoc directory includes a file called stylesheet.css. This text file can be changed to easily change the appearance. The next screen snapshot shows how it looks when I change the .rowColor, .altColor, and the background-color of the body.

I'm not recommending the colors in the above screen snapshot; they're merely intended to demonstrate how easy it is to alter the presentation's appearance.

Conclusion

I like the new default styling and it comes "out of the box" with no new effort as of JDK 7 build 146. This is only a minor and largely cosmetic improvement, but it is nevertheless welcome.

Tuesday, June 21, 2011

This post is a summary of some recent articles and posts related to software development that I have found to be interesting. They cover computer science as a career, the history of programming, the good and bad of Hibernate, mobile apps popularity relevant to web use, the necessity of learning JavaScript, and free electronic books for web developers.

Computer Science: A Top 5 In-Demand Degree

The Yahoo! Education article Top 5 In-Demand Degrees by Chris Kyle references the National Association of Colleges and Employers (NACE) "Job Outlook 2011" and lists "most in demand [degrees] at the bachelor's degree level." Among the five listed bachelors degrees are Engineering (#3), Business Administration (#5), and Computer Science (#4). The average salary for computer scientists is listed as over $100,000 (annual USD).

Mike Rozlog's The History of Programming is an interesting read. Rozlog not only covers the history of programming, but also looks at today and labels it the "land of the mixers" where "instead of coming up with something new, we now add from all different languages to create a new language." He cites Falcon as an example of this. He then briefly speculates on what the future might hold.

I learned several new facts about the history of programming from this article, but what I liked best was how Rozlog articulated something I have long felt:

For over the past 50 years, we have been rehashing the same ideas over and over. Requirements are not shrinking and customer expectations are not withering, so whatever language you choose to complete a project, make sure you like it and it gets the job done.

I could not have said it better myself.

Ten Free Ebooks Every Web Developer Should Have

There is a nice collection of free electronic books briefly summarized and referenced in the post 10 Free Ebooks Every Web Developer Should Have. The cited electronic books cover diverse topics of interest to web developers such as performance, security, web design, search interfaces, accessibility, best practices, web style, and HTML5.

I too have never been a huge fan of JavaScript, but it has been a necessary language to know in any serious web development and I've reluctantly used it on and off over many years of web development. I am glad to see improved libraries and support making it easier to use. Most important to me is that increasing consistency of JavaScript implementations across multiple target browsers. For a Java developer used to "write once run anywhere," JavaScript's different treatment and behavior in different browsers has been maddening.

There seems to be rapidly growing interest in CoffeeScript, described as "a little language that compiles into JavaScript" in "an attempt to expose the good parts of JavaScript in a simple way." The CoffeeScript Cookbook site holds great promise as a repository of "recipes for the community by the community." Another recent post of interest for folks new to CoffeeScript is CoffeeScript Development in 3 mintutes.

Mobile Has Overtaken Web?

Leena Rao's TechCrunch article Flurry: Time Spent On Mobile Apps Has Surpassed Web Browsing references Charles Newark-French's post Mobile Apps Put the Web in Their Rear-view Mirror. Among other interesting observations, the Flurry post states, "In 2011, for the first time, smartphone and tablet shipments exceed those of desktop and notebook shipments" and adds, "Our analysis shows that, for the first time ever, daily time spent in mobile apps surpasses desktop and mobile web consumption." For more details on how these numbers were collected and processed, see the original post. Even if there may be some controversy surrounding the quality of the metrics and how they are gathered, there is no doubt that mobile apps have seen tremendous growth in use in recent years.

The Good, the Bad, and the Ugly of Hibernate

I like Steve Ayers's post Dr. Mindbender, Or How I Learned To Stop Worrying And Love Hibernate because he looks at Hibernate's good and bad points and where its use might make sense and where its use might not make sense. I have seen Hibernate abused fairly badly and its misuse has made things more difficult than they should be because its use was not appropriate. It's also the type of post I like because it demonstrates both a willingness to learn and change opinions and to be more insightful than simply "such and such is great" or "such and such is terrible."

JDK 7 Improvements to Javadoc

Jonathan Gibbons's post What's Up, Javadoc? provides interesting insight into "mostly under the covers" improvements to Javadoc in JDK 7. I especially like the fact that a CSS stylesheet is now used, making it easier to change appearance of Javadoc-generated documentation. Although many of the improvements to Javadoc may be largely internal and not so obvious to most Java developers, just the fact that Javadoc is getting some long-needed attention is encouraging.

PHP One-Liners

After writing the Ten Groovy One Liners to Impress Your Friends, I thought about writing a similar post for PHP because it's the latest language I'm trying to find time to investigate. I quickly realized I still lack the background knowledge required for something like this and that it would take significant effort to put it together. I was therefore happy to see that Martin Šrank has posted 10 PHP One Liners to Impress Your Friends. I believe that one of the advantages of reading posts like this, especially for scripting languages, is the ability to quickly learn some of the common syntax and library support used in various common scripting functions.

Conclusion

In this post, I have referenced some general software development posts of interest as well as a few specific to things like JavaScript and Hibernate. Several of these posts represent the current state of software development.

Monday, June 20, 2011

Package objects contain version information about the implementation and specification of a Java package. This versioning information is retrieved and made available by the ClassLoader instance that loaded the class(es). Typically, it is stored in the manifest that is distributed with the classes.

In this blog post, I look at how Java code can use the Package class to access version information about a particular Java package's specification and implementation.

The Setting Package Version Information page indicates that seven pieces of information (seven lines in the manifest file) can be specified for package version information. The first line of the seven is the name of the package and is indicated by Name. The other six pieces of version information that can be specified are title, version, and vendor for the specification and the same title, version, and vendor for the implementation. An example of what this might look like is shown next in this example MANIFEST.MF file.

The example shows a common section as well as a section specific to the dustin.examples package. Note that I specified Package-Title, Package-Version, and Package-Vendor in the Ant build file and they were included in the resultant manifest file. I'll return to these later in this post.

It is very easy to access the package information at this point. Use of Package.getPackages() to get all packages associated with the current class loader and Package.getPackage(String) to get a particular package by name from the current class loader are demonstrated in the next code listing for Main.java.

The output shows that the package information described in the MANIFEST.MF's file is available to Java code. I intentionally included three attributes in the MANIFEST.MF example above that are not accessible from Java's Package class. These are Package-Title, Package-Version, and Package-Vendor. The Setting Package Version Information page links to the Package Version Specification, which has a section 1.5.8 JAR Manifest Format that shows use of these three attributes beginning with Package- rather than the three I showed earlier beginning with Implementation-. My example intentionally included both sets with different values for each to prove that its the three Implementation- attributes that are available via the Package class rather than the three Package- attributes.

Conclusion

I demonstrated in this blog post how to use Java's Package class to access version information about a particular Java package. To demonstrate this, I used Ant to specify the package version information in a JAR's MANIFEST.MF file as part of the javac task.

Thursday, June 9, 2011

During the course of my Groovy evangelism, I've often been asked what the best book is for a Java developer to use to learn Groovy. Unfortunately, this is another of those dreaded "it depends" answers. In this post, I summarize why I like and regularly use three Groovy books: Groovy Recipes: Greasing the Wheels of Java, Programming Groovy: Dynamic Productivity for the Java Developer, and Groovy in Action. I hope to be able to provide details as to what distinguishes each book from the other two for those looking for a single book. They each offer distinct advantages in addition to many common advantages and I have found each one to be useful in different situations. The good news is that all three books are excellent in their own right so one really can't go "wrong" with any of them.

Groovy Recipes: Greasing the Wheels of Java

Groovy Recipes was the first Groovy book I purchased because I have found the "Cookbook" approach and "Recipe" approach to be a fairly effective way for me to learn a new language through application of practical examples. As much as I like the common "cookbook"/"recipe" style book anyway, I liked the fact that Groovy Recipes provides it recipes in an order that makes it serve as an adequate introductory book as well. In other words, I did not need another book to give me the basics before diving into the Groovy Recipes book.

Groovy Recipes's Table of Contents demonstrates how the chapters and recipes are structured to almost read like an introductory text. Both the book's subtitle ("Greasing the Wheels of Java") and its introductory chapter titles relay the fact that this book begins coverage of Groovy from a Java perspective. Chapter 2 provides a high-level overview of how Groovy builds upon and improves upon Java concepts and syntax. Chapter 3 covers the many different ways one can run simple Groovy scripts as well as IDEs and other basic tooling support for Groovy. Chapter 4 is a great chapter for a Java developer coming to Groovy as it really emphasizes what Groovy adds to Java.

Not only do the initial chapters provide a solid introduction to Groovy, but even the latter and more advanced chapters continue to show off Groovy features via practical applications while at the same time introducing Groovy concepts and syntax at a level appropriate for those with little experience with the language. I use Groovy largely for my scripting needs. As such, the practical recipes related to Groovy on the command line (Chapter 6) and Groovy's file handling (Chapter 7) are important to me. I also spent a lot of time in Chapters 8 and 9 reading about Groovy's fantastic XML parsing/slurping and writing capabilities. Finally, the latter chapters of this book cover Groovy's metaprogramming capabilities before ending with two chapters focused on Grails.

Groovy Recipes is an excellent book with a recipes-oriented format that is seamlessly woven into introductory-feeling flow. It's a great combination. The only drawback is that Groovy Recipes does not cover as much as Groovy as the other two books I am writing about in this post. For example, I often find myself performing database access from my Groovy scripts and this book has very little to offer in that area.

Groovy Recipes covers a lot and what it covers, it covers well. However, it does not cover some topics and so I found I needed another Groovy book as a supplement. That being said, I liked this book so much, I bought it twice! (I lost the first copy through a not-so-smart move and missed the book enough that I bought it again.) This is the book that "hooked" me on Groovy and got me excited about what I could do with the language as a scripting language. I still use this book, particularly when working with command-line, with files, or with XML in Groovy. This book has the most impressive cover of the three books I review here and, in fact, has one of the most impressive covers I've seen on a programming language book.

Programming Groovy: Dynamic Productivity for the Java Developer

Like, Groovy Recipes, Programming Groovy is brought to us from The Pragmatic Programmers as part of The Pragmatic Bookshelf. In fact, the authors of this book and of Groovy Recipes were originally going to write a single book between them and decided that their respective focuses and intentions warranted two separate books. After reading most of both books, I agree that the different treatment was a good idea as both books provide distinct advantages

Programming Groovy is exactly the type of book one would want if looking for an introductory book that quickly builds on basic concepts. It is well written and follows the "classical" language introduction approach. The Programming GroovyTable of Contents shows that this book starts out with high-level background information on what Groovy addresses as a language and why a developer might want to read more about and learn more about Groovy.

The second chapter of Programming Groovy covers acquiring Groovy and getting a basic Groovy development environment set up. Chapter 3, "Groovy for the Java Eyes," provides a nice introduction to Groovy targeted specifically at Java developers. I found it interesting that this book addresses dynamic typing (Chapter 4) and closures (Chapter 5) before looking at Strings (Chapter 6) and Collections (Chapter 7). The obvious reason for this is that Groovy GDK and other extensions to String and to the Collections are largely based on the dynamic typing and especially the closure features. These first seven chapters are contained in Part I ("Beginning Groovy") and cover the basics of Groovy.

Part II ("Using Groovy") is the more "practical" portion of the book. Chapter 8 of Programming Groovy covers the highly important and highly useful GDK. Chapter 9 covers Groovy's fabulous XML support and Chapter 10 gives me the coverage of "Working with Databases" that I was wanting. Chapter 11 covers writing scripts and classes in Groovy as well as using Groovy and Java together.

Part III ("MOPping Groovy") is the most advanced portion of Programming Groovy. In this part, Groovy's Meta-Object Protocol (MOP) gets extensive coverage in two chapters. Other chapters cover DSL creation, unit testing, and the all-important Groovy builders.

Groovy in Action

Groovy in Action is the largest and most comprehensive of the Groovy books covered in this review. When Groovy Recipes doesn't cover a particular topic and when Programming Groovy doesn't cover it either, I can typically count on it being covered in this book. There is one caveat to that: the topic I'm looking for must have been part of Groovy for a while. Groovy in Action happens to be the oldest of the three books covered here and in some areas it's showing its age. The good news is that the Second Edition of Groovy in Action is anticipated to be delivered in Summer 2012 and is available in in-work form now via the Manning Early Access Program (MEAP). I have high hopes for combining the comprehensive nature of the first edition with newer topics and features also covered. The current cover of the Second Edition shows it being applicable to Groovy 1.7.

The Groovy in ActionTable of Contents gives a small test of the thorough coverage of Groovy provided by this book. The fact that the publisher is pursuing a Second Edition is a testament to the selling power of this book. Besides its completeness, another advantage of the book is the high degree of expertise involved. The multiple authors have been key contributors to Groovy's development.

Conclusion

All three books covered in this post are excellent Groovy introductions and references. For pure reference, Groovy in Action may be the strongest due to its comprehensive coverage. For introductory material, Programming Groovy may be the strongest. For seeing how to apply Groovy quickly in daily scripting tasks, Groovy Recipes is probably the best. They are all excellent and I've found all of them to be useful many times over.

Tuesday, June 7, 2011

I discuss two convenient Groovy language operators for concisely dealing with elements of Groovy collections in this blog post. In particular, this post focuses on Groovy's spread-dot operator and its spread operator.

Both approaches shown above produce the same result: all items in the collection being acted upon are multiplied by two. The spread-dot operator makes it possible with a small number of characters to apply the same method (multiply in this case) on all entries of the collection. The result both implementations produce is: [2, 4, 6, 8, 10, 12, 14, 16, 18, 20].

There is another difference between the approach that I used and the approach Herrero used. With the explicit Collection.connect(Closure) method, a closure was used to explicitly multiply each entry by two. The spread-dot operator approach did not use an explicit closure, but instead specified the multiply method should be performed on each entry in the collection. The numeric types in the collection supported the multiply method. The spread-dot operator supports field specification and property specification in addition to method specification.

Another example using the spread-dot operator is shown in the next code listing. It is on a collection of strings and a String-specific method, toUpperCase() is used on each element of the collection via the spread-dot operator.

['Denver', 'Cheyenne', 'Reno', 'Sacramento']*.toUpperCase()

When the above is executed and printed out, the results looks like this: [DENVER, CHEYENNE, RENO, SACRAMENTO]. The spread-dot operator allowed toUpperCase() to be applied to each String-based entry in the collection.

Spread Operator (*)

The spread operator is related to the spread-dot operator, but its purpose is to extract entries from a collection and provide them as individual entries. This can be useful for converting collections to individual parameters on method calls. An example should make this clearer. In the next code listing, a Groovy Collection of values destined for a Calendar.set(int, int, int, int, int, int) method is passed to that Calendar method as six arguments via the spread operator.

Both of the two examples of the spread operator were applied to the Java classes Date and Calendar. The spread operator works in Groovy code whether it's being used to invoke Groovy or Java methods.

Beware the MissingMethodException

Incorrect use of both the spread-dot operator and the spread operator can lead to the throwing of a MissingMethodException. This exception is typically encountered with the spread-dot operator when the method, field, or property being accessed in conjunction with the spread-dot operator is attempted against an entry that does not support that method, field, or property. For example, if a number without strings had been added to the collection of city name Strings above, this exception would be encountered when the operator attempted to invoke String.toUpperCase() on the numeric type.

The MissingMethodException can also be encountered when using the spread operator if the collection the spread operator is applied to has a different number of arguments than those expected by the method or constructor being invoked. For example, if I had added some arbitrary integers to the end of the six integers intended for the Date/Calendar examples, this exception would have been encountered because none of their respective set methods/constructor expect more than six integers.

Conclusion

Groovy's spread and spread-dot operators can make use of individual items within a collection easier and more concise than explicitly performing the same functionality. In this post, I looked at how the spread-dot operator makes it possible to apply the same method (or access the same field or property) to all entries of a collection and how the spread operator makes it possible to automatically convert a collection to individual pieces for use in code expecting individual pieces rather than an entire collection.

There are several reasons single line code examples can be useful. First, they can be useful in production software when they provide less code without sacrificing readability. Not all single lines of code can pull this off, but it's highly desirable when they do. Most of my examples in this post are simple to read and understand, but perform the expected function in one (often short) line. A second benefit of single line solutions is that they demonstrate certain features, library calls, and syntax of programming languages. A particular advantage of single-line solutions for Groovy and some other languages is the ability to invoke the single line from the command line. This is done in Groovy with the -e option and I intend to use groovy -e to demonstrate all ten examples in this post.

The ten scripts demonstrated in this post are very simple and largely demonstrate Groovy's rich features. Many of these functions could be implemented with operating system commands or shell scripts, but an advantage to performing these via Groovy is that all of these particular scripts are independent of operating system and should work on any operating system on which a Java Virtual Machine is supported. Where these single lines would most likely be used would be within larger scripts used in the development environment.

1. List JVM Available TimeZone IDs

The TimeZones provided by each JVM are provided with String names. The supported TimeZones for a particular JVM can be easily identified with the following single line of Groovy.

TimeZone.getAvailableIDs().sort().each{ println it }

The next screen snapshot shows execution of this single line of Groovy code via groovy -e.

2. Binary File Copying

Copying a file with a single line of Groovy is nifty. There's more than one way, but the approach shown here works even for binary files.

new File("NewWordDocument.doc").bytes = new File("WordDocument.doc").bytes

The next screen snapshot shows that this works.

3. Acquiring Host Information

Groovy makes it easy to use Java's InetAddress class to determine information about the host. I show two examples of Groovy scripts taking advantage of this class. The code examples are followed by the screen snapshot showing execution of the two commands on the command line. Note that I did some character escaping on the second example as part of its running in the DOS terminal.

The Groovy GDK's Date class provides a significant convenience in this example.

println new Date().dateTimeString

5. Display Contents of JAR Manifest File

I covered use of Groovy to see a Manifest file's contents in the blog post Viewing a JAR's Manifest File. The example I showed there is repeated here. In this case, I use a Lucene JAR, but it could any JAR or WAR or EAR file.

This post provides a small taste of how Groovy can support significant functionality with concise but expressive syntax. These examples are very simple in large part due to Groovy's convenience methods, especially as provided in the GDK.

This post summarizes some blog posts that I have found very interesting in the past week (posts may be older than this, but I saw them in the past week). The topics covered are fairly diverse.

Learning Groovy

I like Vasanth Dharmaraj's post Learning Groovy for a couple reasons. One obvious reason that I like this post is that Dharmaraj specifically references my blog. However, even if he had not done so, I still like it for a second reason: his description of his own experience with Groovy articulates what I have witnessed that many Java developers (includes myself) who aren't big on scripting feel when starting to use Groovy. He starts his post with this: "I have dabbled a bit with scripting languages before but for some reason never really used one long term. I think that might change with Groovy." The remainder of the post provides examples of how he was able to use Groovy to accomplish scripting tasks concisely. I have come to the same conclusion as Dharmaraj regarding Groovy use in a development environment: "Come to think of it Groovy could have saved me a ton of time I spent in writing small tools to help me in development."

Ten One Liners in Your Favorite Language

There was an interesting explosion of blog posts covering examples in different programming languages of single line solutions. It all started with the Scala post, but led to several other languages being covered as well. I found them interesting enough to motivate me to write the post Ten Groovy One Liners to Impress Your Friends. Here is a rundown of the posts that I am aware of as of this writing:

Because these posts generally implement the same solution in the different languages, it is an entertaining and enlightening experience to read the syntax and library use in the various languages and compare them. Although I don't use one-liners like these regularly, being able to read and compare them helps to learn more about my favorite languages as well as more about languages I know very little about.

CS-Script is a CLR (Common Language Runtime) based scripting system which uses ECMA-compliant C# as a programming language. CS-Script currently targets Microsoft implementation of CLR (.NET 2.0/3.0/3.5/4.0) with limited support on Mono. CS-Script combines the power and richness of C# and FCL with the flexibility of a scripting system. CS-Script can be useful for system and network administrators, developers and testers. For any one who needs an automation for solving variety of programming tasks.

From this description, it sounds like CS-Script exists to meet the same needs in the C# area that Groovy serves in the Java area.

PHP Performance Tips

Eric Higgins has posted PHP performance tips which details "changes that you can make very quickly and painlessly" to "improve the performance of your PHP scripts." He covers things like upgrading the version of PHP and profiling PHP.

Windows Command Line Arguments

The post Everyone quotes command line arguments the wrong way discusses "popular solutions" that are "clear, simple, and wrong" before providing a "correct solution." This is very useful information for running Groovy and other scripts in a Windows environment.

DZone DevOps Site

DZone has added a new "Zone" called DevOps Zone with the subtitle "Bridging the Gap Between Development and IT." This new DevOps Zone features a graphic with overlapping circles that indicate "DevOps" is the integration/overlap of Development/Software Engineering with Quality Assurance and Technology Operations. It also includes a link to the What Is This Devops Thing? post.

C++/Java/Go/Scala Performance Compared

The Loop Recognition in C++/Java/Go/Scala paper generated a lot of buzz on the web recently. As its title suggests, it covers "a well speciﬁed, compact benchmark in four programming languages, namely C++, Java, Go, and Scala." The "Conclusions" section of the paper reaffirms what many of us already believed about the various languages, but it is interesting to see the methodology used and to read the observations. Nothing about it is changing my current language plans.

The post Bing, Google and Yahoo! announce Schema.org calls out the recent announcement that the three dominant search engine vendors are collaborating on an initiative to "create and support a common set of schemas for structured data markup on web pages." The stated purpose for Schema.org is:

A shared markup vocabulary makes easier for webmasters to decide on a markup schema and get the maximum benefit for their efforts. So, in the spirit of sitemaps.org, Bing, Google and Yahoo! have come together to provide a shared collection of schemas that webmasters can use.

In its current form, Schema.org's sole supported format is HTML Microdata. The Getting Started page states: "You use the schema.org vocabulary, along with the microdata format, to add information to your HTML content. While the long term goal is to support a wider range of formats, the initial focus is on Microdata."

In the post The False Choice of Schema.org, Manu Sporny acknowledges that the Schema.org announcement "may sound good on the surface," but then argues that "it is very bad news for choice on the Web." Sporny starts with the disclaimer that he is biased and acknowledges his interest in RDFa, but states that he makes the arguments outlined in his post because he has "been around long enough to know when freedom of choice on the Web is being threatened."