Tuesday, September 13, 2011

More JavaOne 2011 News - 13 September 2011

As JavaOne 2011 approaches, more blog posts regarding JavaOne 2011 attendance are being posted. This post references and briefly summarizes some of these posts. I posted two similar posts previously on August 6 and August 29.


Java.net at JavaOne 2011

The Tori Wieldt post Java.Net at JavaOne references a note from Sonya Barry (Java.net Community Manager). The post mentions some of the people from Java.net who will be at JavaOne 2011 as well as some of the activities they will be attending.

Java.net editor Kevin Farnham has posted Informal Chats at JavaOne 2011: You're Invited! He writes:

Having missed last year's JavaOne, there's lots of catching up I'd like to do with lots of people at JavaOne 2011. ... I don't want to rely solely on chance for meeting up with people. So, I'd like to arrange in advance times when I'll meet some people for informal chats. As we chat, I'll take notes, and ultimately I'll include it all in a java.net blog.


JavaOne 2011 Diversity

Don's post The incredible Diversity of JavaOne says of JavaOne 2011, "As a relatively new Product Manager in the SE team, there’s absolutely no shortage of areas I could focus on. ... One thing that has struck me from reading the program though, is the incredible diversity of the Java Ecosystem." Don emphasizes with examples the diversity of organizations at JavaOne 2011 as well as the diversity of the worldwide Oracle development labs represented at the conference.


JavaOne 2011: It's About NetBeans

The page NetBeans at the JavaOne 2011 Conference lists sessions at JavaOne 2011 related to NetBeans. Some of the listed presentations include How to Refactor for JDK 7, NetBeans Project Management, and The Hitchhiker's Guide to NetBeans RCP. In the blog post Focus On Developer Tools – NetBeans IDE, Pieter Humphrey provides a list of technical sessions, hands-on labs, Birds of a Feather sessions, and booths related to NetBeans at JavaOne 2011. By the way, he has a similar post for JavaOne 2011 and Oracle OpenWorld 2011 focus on Eclipse.


JavaOne 2011: It's About Architecture

In Architects and Architecture at JavaOne 2011, Bob Rhubart provides "a sampling of the more than 225 JavaOne sessions for architects." Presentations listed in his post cover Sunday through Thursday of the conference. The presentations he lists include GlassFish Unconference—Let Your Voice Be Heard, NoSQL Versus Relational Database: Showdown Between a Java Developer and a DBA, Don't Call Us; We'll Push You: The Story of Cross-Tier Push Architecture, Domain-Driven RESTful APIs at LinkedIn, Relational Won't Cut It: Architecting Content-Centric Applications for Java, REST and Hypermedia as the Engine of Application State with Standard Java APIs, RESTing Hard: Enterprise-Strength REST for Java, and Rapid RESTful Web Applications with Apache Sling and Jackrabbit.


JavaOne 2011 Group Discounts

Although it doesn't have the same ring to it as BOGO, organizations that purchase four JavaOne passes can get a fifth one free (BFGO). The details of this offer are available in JavaOne Group Discount - Share the experience and save $1795!

Saturday, September 10, 2011

Book Review: The Mythical Man-Month: Essays on Software Engineering, Anniversary Edition

Frederick P. Brooks, Jr.'s The Mythical Man-Month (MM-M) is one of the most famous books in all of software development literature and is arguably THE most famous book on software development management. There are already innumerable reviews of this classic, but I review it again in this post for those software developers who have not read it and want a small overview of what's to like about it. After all, it is PC World's #1 title in the list of Top Ten IT Books Never To Admit You Haven't Read. The full title of the edition I am reviewing in this post is The Mythical Man-Month: Essays on Software Engineering, Anniversary Edition.

The "Anniversary Edition" of The Mythical Man-Month (published in 1995) adds significant content above and beyond what was published in the original edition in 1975. The "Anniversary Edition" contains the original book in its original form (albeit with the inclusion of corrections added in the 1982 reprint) and adds four new chapters. The first fifteen chapters in the Anniversary Edition are the chapters from the original book. The added chapters include Brooks's separate but equally famous IFIPS (1986) / IEEE Computer Magazine (1987) paper No Silver Bullet: Essence and Accidents of Software Engineering and a follow-up called No Silver Bullet ReFired. Chapters 18 and 19 of the Anniversary Edition focus on Brooks's 1995 self-perspective on what he wrote in 1975. Brooks points out what he got wrong and what he got right (there are far more cases of the latter than the former).

There are numerous reviews of The Mythical Man-Month that include exhaustive coverage of the topics and quotes from this book (Wikipedia article, Bernard I. Ng's The Mythical Man-Month summary, Some insights from The Mythical Man Month starting from Chapter 11, The Mythical Man-Month – Extracts I, The Mythical Man-Month – Extracts II, The Mythical Man-Month Lecture, and Review/Summary of The Mythical Man-Month, for example). Rather than repeat an overview of the book's content as a whole, I focus in this post on a few key points and in light of some modern day software best practices and ideologies.

Chapter 19 ("Propositions of The Mythical Man-Month: True or False?") of the "Anniversary Edition" will especially appeal to the reader who is impatient or lacks the time to read the entire book, but wants to get an overall view of Brooks's assertions. Because Brooks uses this chapter to present "the essence of the 1975 book" in "outline form," Brooks's assertions ("facts and rule-of-thumb-type generalizations from experience") from his original book are presented in "stark form" (approximately 20 pages). The presence of this chapter in the "Anniversary Edition" is another reason I don't break the book down chapter-by-chapter here. This chapter does more than simply summarize the assertions from the original book; it also includes some of Brooks's 1995 comments based on 20 more years of observation and the benefit of hindsight.

In his post The Mythical Man Month: Book Review, Mark Needham concludes his review of this book with the statement, "I really enjoyed reading this book and seeing how a lot of the ideas in more modern methodologies were already known about in the 1980s and aren’t in essence new ideas." I wholeheartedly agree with this statement, though the truth of it is possibly even more staggering: these were observations in a book published in 1975 based on Brooks's experiences working on OS/360 development in the mid-1960s and on follow-on conversations in the late 1960s. In other words, some of the things we might think are "new" or "trendy" today have been around and known for 45 years or more! As a side note, this reminds me of an Alan M. Davis presentation to the Denver Java Users Group ("What's New About New Methods of Software Development?") in late 2006 in which he demonstrated how many of the "new" methodologies and tactics of today have very similar predecessors in years past and how we seem to cycle between them over decades.

The following points made by Brooks are especially interesting when one keeps the thought in the back of his or her mind that this book was published in 1975 based on experiences in the mid- to late- 1960s (these quotes are from the Chapter 19 summarization but are based on text in the 1975 edition):

  • "Very good professional programmers are ten times as productive as poor ones..." [craftsmanship]
  • ""A small sharp team is best - as few minds as possible." [agile]
  • "Fixing a defect has a substantial (20 to 50 percent) chance of introducing another. After each fix, one must run the entire bank of test cases previously run against a system to ensure that it has not been damaged in an obscure way." [regression testing]
  • "It is worthwhile to build lots of debugging scaffolding and test code, perhaps even 50 percent as much as the product being debugged." [unit testing]
  • "To keep documentation maintained, it is crucial that it be incorporated in the source program, rather than kept as a separate document ... even high-level language syntax does not at all convey purpose." [DRY principle]

There are many more observations in The Mythical Man-Month that demonstrate that Brooks and other developers of the time understood many of the same basics of software development that we understand (and sometimes "discover" again) today. Many of these are more well-known and are called out in other reviews and so I don't list them here except for these must-list quotes:

  • "More software projects have gone awry for lack of calendar time than for all other causes combined."
  • Brooke's Law: "Adding manpower to a late software project makes it later."
  • "Hence the man-month as a unit for measuring the size of a job is a dangerous and deceptive myth."

One of the sections I found particularly timely (especially for a 1975 book in 2011) was Brooks's coverage of how a software architect can influence implementation. This can be especially sensitive when the architect's vision is not implemented by the developer in the way the architect desired. Brooks's tips seem very practical. He states that the architect must come to terms with the fact that the person implementing the code has "creative responsibility" for that implementation. He further advises that the architect should always have an idea of how to implement any of his or her designs, but must at the same time be willing to accept an equally good alternative approach proposed by the person implementing the code. Brooks further recommends that the architect make all suggestions regarding implementation "quietly and privately," be "ready to forego credit," and be willing to listen to the implementer's "suggestions for architecture improvements." This seems like sound advice to me based on my experiences on both sides of this relationship.

In the 2005 article Quoted Often, Followed Rarely, Brooks states:

The book is really more about management than about technology. The technology has changed immensely, so some of the old chapters are totally out of sync. On the other hand, people haven't changed much. That's why Homer and Shakespeare and the Bible are still relevant, because they're all dealing with human nature. I think that's part of the explanation for this book: The problems of managing people in teams have not changed, though the medium in which people are designing and the tools they are using have. Some people have called the book the "bible of software engineering." I would agree with that in one respect: that is, everybody quotes it, some people read it, and a few people go by it.

The concepts contained in this quote may be the most important thing to convey in a review of The Mythical Man-Month. The appeal of the book is its coverage of and focus on management of people. That has remained timeless and unchanged over the decades. The technologies have definitely changed significantly and that may be the biggest negative about this book. Brooks's examples based on specific products, tools, and languages in 1975 were certainly more illustrative then than they are today for the typical reader. For example, his 1975 book calls PL/I "the only reasonable candidate for system programming today." At times, some of the reading can be a little more challenging with lack of direct experience with the products of which Brooks mentions. However, in most cases, this is not much of a hindrance in the end because of the human element is the focus of the book and this is mostly unchanged even now. In Chapter 19 of the Anniversary Edition, Brooks reflects on the continuing popularity of his book and states: "to the extent that The MM-M is about people and teams, obsolescence should be slow."

The Mythical Man-Month is really about very large enterprise software development projects. This is important to bear in mind when reading things that may seem obvious to someone working on a small project. The last part of the quote above is famous: "Some people have called the book the 'bible of software engineering.' I would agree with that in one respect: that is, everybody quotes it, some people read it, and a few people go by it." Brooks's book is filled with Biblical references and he is obviously acquainted with the Holy Bible. Sadly, Brooks's quote "everybody quotes it, some people read it, and a few people go by it" is all too true today. We'll keep reading it, but it'd be nice to do more to change things in large-scale software development projects.

Some people feel that The Mythical Man-Month is defeatist and even depressing. I don't get the same feeling from reading it. Rather, I feel that it reminds us that certain behaviors are detrimental and dysfunctional. It also reminds us that we shouldn't wait for the "next big thing," but should instead continue to improve our craft as best we can. Many practical tips and suggestions are provided. Brooks obviously loves being in the software development field and this is shown again and again in his book. Brooks concludes the book's "Epilogue: Fifty Years of Wonder, Excitement, and Joy," talking about how he used to be able to "read all the journals and conference proceedings," but eventually had to give up specific interests one by one as the knowledge exploded. He concludes, "Too many interests, too many exciting opportunities for learning, research, and thought. What a marvelous predicament! Not only is the end not in sight, the pace is not slackening. We have many future joys." I definitely agree.

Thursday, September 8, 2011

Java Lambda Syntax Announced

Brian Goetz's OpenJDK message Syntax Decision (on the lambda-dev mailing list) provides the "(mostly)" decided syntax for Java lambda expressions. Goetz caveats this announcement ["We may still deliberate further on the fine points (e.g., thin arrow vs fat arrow, special nilary form, etc), and have not yet come to a decision on method reference syntax"] before providing some examples of how the C#/Scala-inspired syntax would look.

Goetz states reasons for selecting the syntax such as doing well by "subjective measures" and Java being similar to the syntax of two highly related (syntactically) languages (C# and Scala) in the absence of a clearly preferred syntax choice.

Other interesting resources related to Java and the long road to lambda support include First Version of Java Lambda Syntax Sparks Debate, Lambdas in Java: An In-Depth Analysis, Understanding the closures debate, and Project Lambda: Straw-Man Proposal.

Tuesday, September 6, 2011

Groovy's Special Words

The Java Language Keywords are words that cannot be used "as identifiers in your programs." The Java Tutorial states regarding Java keywords, "The keywords const and goto are reserved, even though they are not currently used. true, false, and null might seem like keywords, but they are actually literals; you cannot use them as identifiers in your programs." In other words, the greater set of words that cannot be used as identifiers in Java code are "reserved words" including the keywords plus true, false, and null.

It is not surprising that Groovy "inherits" Java's reserved words. However, Groovy adds some of its own as documented in the Reserved Words section of the Groovy User Guide. This section highlights that Groovy adds the following words to the set of Java reserved words: as, def, in, and threadsafe. Three other words that I treat as "reserved words" when writing Groovy scripts are the closure-related implicit names delegate, it, and owner. Other special Groovy "words" are use and with provided by Groovy's Object class. I cover these nine "special" Groovy words in this post.


it, delegate, owner

The three keywords it, delegate, and owner are used with Groovy closures. They provide handles to implicitly available objects from within the closure's body. Although these keywords can be used outside of the closure body for other purposes, I tend to reserve them for use within a closure. In fact, one can even use them for purposes other than their intended purpose within a closure body, but this seems to be especially poor taste to do.

For closures accepting a single argument, the keyword it can be used to represent that single parameter rather than explicitly specifying the single parameter's name. The keywords this, owner, and delegate also have special meaning within a closure.


as

There are multiple uses of the as keyword in Groovy. In The Groovy 'as' Keyword, Daniel Silva provides examples of using the as keyword to coerce a type (prettier cast) and to create an alias for an import statement (as of Groovy 1.5). Steven Devijver's post Higher-order functions with Groovy, part 2 talks about using the as keyword used "on closures to turn them into interface implementations" using java.lang.reflect.Proxy.


in

The in keyword is sometimes used in Groovy to ascertain whether an object is contained within a collection. A nice example of this is demonstrated in the post The Groovy 'in' Keyword. The in keyword is often used in Groovy in conjunction with iteration/looping. The StackOverflow thread How does the Groovy in operator work? states that "it looks like the in operator is based on the isCase method" and that Groovy's collections' contains() methods are called by isCase.


def

The def keyword is frequently seen in Groovy code listings. The What is this 'def' I've Heard Of section of Scoping and the Semantics of 'def' in the Groovy User Guide has this to say about def:
"def" is a replacement for a type name. In variable definitions it is used to indicate that you don't care about the type. In variable definitions it is mandatory to either provide a type name explicitly or to use "def" in replacement. This is needed to the make variable definitions detectable for the Groovy parser.
This documentation also specifies a rule of thumb for thinking about def: "think of 'def' as an alias of 'Object'."

There are some nuances with the use of def depending on whether the Groovy code is a script or a class. I blogged on this in the post Visible Script Variables: Using Groovy 1.8's @Field AST in which I showed how Groovy 1.8 made it possible to use def in Groovy scripts and still have the defined variable available to methods on the script.


threadsafe

I was curious about threadsafe when I saw it on the list of Groovy reserved words because I did not recall seeing it in any code samples. It turns out there's a reason for this: Guillaume Laforge stated that the threadsafe keyword is a "reserved word we've never used so far" (16 August 2007).


use

The use keyword is applicable when using Groovy Categories as illustrated in the Pimp My Library Pattern example and as illustrated in my concisely named post Adding Common Methods to JAXB-Generated Classes (Separate Class/Groovy Categories).

The use "keyword" is actually NOT a keyword, but is a method on Groovy's GDK extension of the Object class and is provided via Object.use(Category, Closure). There are numerous other methods provided on the Groovy GDK Object that provide convenient access to functionality and might appear like language keywords or functions because they don't need an object's name to proceed them. I tend not to use variables in my Groovy scripts with these names (such as is, println, and sleep) to avoid potential readability issues.


with

The Groovy GDK Object provides another method that I want to focus on here. The with(Closure) method allows us to group method calls and property accesses to a single object.


Conclusion
I have covered special Groovy words in this post that are either reserved words (in addition to Java reserved words) or are special handles by which greater functionality is invoked in Groovy. In general, I avoid using these words as identifiers or as names of my own methods. Although some of them are allowed for such uses,I generally avoid doing this to maintain readability. Groovy even allows for Java keywords to be overridden by method names, but I likewise don't typically take advantage of this.

Thursday, September 1, 2011

Checking for Null or Empty or White Space Only String in Java

.NET Framework 4 introduces a new method on its String class called IsNullOrWhiteSpace that checks whether a provided String is null, empty, or consists only of "white space." This handy method is in addition to the method IsNullOrEmpty that has been available since .NET 2. These potentially very useful (and commonly used) methods are not part of Java's standard JDK String, but in this post I look at how Apache Commons Lang and Guava provide methods similar to these or from which methods similar to these can be easily written.

A typical "standard Java" approach for detecting whether a String is null, is empty, or consists solely of white space is as shown in the next code listing.

Java Approach
/**
 * Demonstrate checking for String that is not null, not empty, and not white
 * space only using standard Java classes.
 *
 * @param string String to be checked for not null, not empty, and not white
 *    space only.
 * @return {@code true} if provided String is not null, is not empty, and
 *    has at least one character that is not considered white space.
 */
public static boolean isNotNullNotEmptyNotWhiteSpaceOnlyByJava(
   final String string)
{
   return string != null && !string.isEmpty() && !string.trim().isEmpty();
}

In the above example, one might compare length of Strings rather than call the isEmpty() method. There are other approaches as well including using regular expressions. Also, the code could be made more concise by not having the individual check for emptiness and simply doing that via the trim().isEmpty() call.

The Google Guava library can also be used effectively for determining a non-null, not empty String with at least one non-whitespace character. An example of that is shown next.

Guava Approach
// import com.google.common.base.Strings;
/**
 * Demonstrate checking for String that is not null, not empty, and not white
 * space only using Guava.
 *
 * @param string String to be checked for not null, not empty, and not white
 *    space only.
 * @return {@code true} if provided String is not null, is not empty, and
 *    has at least one character that is not considered white space.
 */
public static boolean isNotNullNotEmptyNotWhiteSpaceOnlyByGuava(final String string)
{
   return !Strings.isNullOrEmpty(string) && !string.trim().isEmpty();
}

The Guava approach above uses the "standard Java" approach for determining that the String is not white space only. However, Guava provides the convenient Strings.isNullOrEmpty(String) static method for determining if a given String is null or empty.

The example using Apache Commons Lang is simplest and most concise approach as depicted in the next code listing.

Apache Commons Lang Approach
// import org.apache.commons.lang.StringUtils;
/**
 * Demonstrate checking for String that is not null, not empty, and not white
 * space only using Apache Commons Lang classes.
 *
 * @param string String to be checked for not null, not empty, and not white
 *    space only.
 * @return {@code true} if provided String is not null, is not empty, and
 *    has at least one character that is not considered white space.
 */
public static boolean isNotNullNotEmptyNotWhiteSpaceOnlyByCommons(
   final String string)
{
   return StringUtils.isNotBlank(string);
}

With Apache Commons Lang, one simple call does it all! The StringUtils.isNotBlank(String) static method does exactly what we wanted in this particular case: check a String to ensure it is not null, not empty, and not white space only. Its Javadoc documentation says as much: 'Checks if a String is not empty (""), not null and not whitespace only.'

The above approaches and variations on the above approaches can be used in Java to determine if a String is not null, not empty, and not white space only. They are easy to employ and the Apache Commons Lang approach is particularly concise. However, it would be nice to have this support as a standard part of the Java String. It is difficult for me to finish a post without talking about Groovy, so now I transition to the ability to use Groovy's dynamic support to "add" methods to Java's String class to support this check.

The Groovy code in the next code listing shows how an instance method could be added to String to check for these conditions. In this case, I'm borrowing from Apache Commons Lang's name for the method and using isNotBlank() for the injected method name.

Using metaClass.methodMissing to 'Add' isNotBlank() Method to String
java.lang.String.metaClass.methodMissing=
{ String name, args ->
   if (name == "isNotBlank")
   {
      // Do NOT need to check for null because this method could not have been
      // invoked on a null String. Groovy's GDK extension of String has the
      // isAllWhitespace() method that returns {@code true} for all white space
      // including empty String.
      return !delegate.isAllWhitespace()
   }
}

The above Groovy snippet will inject an "isNotBlank()" method on String instances when invocations of a method of that name are not resolved (missing method). I don't have a null check because an instance method, by its nature, will only work on a non-null instance. The reason the methods discussed previously checked for null is that they were static methods working on a provided instance (and not themselves). With Groovy clients and the safe navigation operator, this is not as much of a deal-breaker as it might be in Java. The example above also demonstrates a method that Groovy's GDK extension of String provides: isAllWhitespace().

An advantage of the above instance-level approach is that we can ask the String itself if it is empty of white space. As you may have noticed, one did not need to intercept String in Groovy to implement this method as the isAllWhitespace() method Groovy provides on the GDK extension of String actually counts an empty String as being all white space.

Suppose that we want to use a static method in Groovy like the Java examples shown earlier so that null can be handled as well. Because this is Groovy, we could simply use the Apache Commons Lang class or the Guava class just as we did in Java. For realistic purposes, that would be a good approach. But for showing off Groovy's grooviness, the next approach is preferable. In this case, a new static method is defined on String that implements the check we have seen above. This enables Groovy client code to call a static method directly on String itself for the check.

Using metaClass.static to 'Add' New Static Method to String
java.lang.String.metaClass.static.isNotNullNotEmptyNotWhitespaceOnly=
{ String string ->
   return string != null && !string.isAllWhitespace()
}

This last example makes it possible to call String.isNotNullNotEmptyNotWhitespaceOnly(String) on any String from Groovy code to check it for being not null, not empty, and not white space only. It also demonstrates how to inject a static method into an existing object in Groovy.


Conclusion

It would be a minor added convenience if standard Java had a class and/or methods added to check Strings for more common conditions. Java 7 has added the Objects class for performing some very common functionality on Objects, so a new class called Strings or StringUtils might do the same thing for Java Strings.