Monday, September 30, 2013

JavaOne 2013 Vicariously

I was disappointed that I was not able to attend JavaOne 2013, but was happy to see numerous useful posts covering this annual conference. In this post, I link to many of these resources and provide a brief summary of what each post discusses in relation to JavaOne 2013.

Keynotes

The keynotes are where the "big announcements" tend to occur. Fortunately, several online posts quoted key portions of the keynotes and provided different perspectives on what was said and the implications of the announcements. I group these references by order of my favorite keynotes at JavaOne: technical, strategy, and community.

JavaOne 2013 Technical Keynote

Java 2013 Strategy Keynote

JavaOne 2013 Community Keynote

Technical Sessions

Several blog posts have been written about specific technical presentation sessions, birds of a feather sessions, and hands-on lab sessions.

Overall Impressions and Summaries

This set of links is to posts summarizing the conference as a whole and relaying attendees' perspectives on the overall conference.

Kevin Farnham's (java.net) JavaOne 2013 Impressions

Kevin Farnham, managing editor at Java.net, has been posting his impressions from JavaOne 2013 in his editorials alongside the posts he references from Java.net.

Conclusion

This year's JavaOne appears to have continued many of the themes discussed at last year's JavaOne including GPUs, Raspberry Pi, Java SE 8 (especially lambda expressions), Java EE 7, NetBeans, OpenJDK, and JavaFX. Of course, there were new announcements related to these themes that included DukePad, open sourcing of Project Avatar, and new OpenJDK participants (Freescale, Linaro and Square)

Saturday, September 21, 2013

My Favorite Books for Advanced Java Developers

The idea for my last blog post (my ten favorite online resources for advanced Java developers), was inspired by the Xiaoran Wang post Top 10 Websites for Advanced Level Java Developers. Wang also wrote a post called Top 10 Books For Advanced Level Java Developers. As with the post on best websites for advanced Java developers, it is easy to see why Wang listed the ten books he did list. In this post, I look at my top ten list which includes many of the same books as on his list, but my list has a few that are different.

There are numerous good (and some not so good) books aimed at beginning Java developers. However, it seems far more difficult to find good Java books for intermediate and advanced developers. There are plenty of books that provide in-depth coverage on very narrow topics and so are suitable for advanced Java developers, but there seems to be few "more general" Java books aimed at advanced developers.

5. Java Generics and Collections

I think many Java developers would say that using Java collections is easy and that using generics can range from easy to difficult depending on what you're doing. However, there is much in Java Generics and Collections (O'Reilly, 2006) to appeal to the advanced developer in its coverage of both generics and collections. The authors of this book point out useful practices related to generics as well as outlining which collections to use in different situations. Even some experienced Java developers may not always consider which collections to use in a particular situation as carefully as they should and this book provides insight into advantages and strengths of each major Java standard collection as well as the drawbacks of each. The book delves deeply into the quagmire of generics and outlines important considerations such as the get and put principle.

4. Java Performance

Charlie Hunt's and Binu John's Java Performance (Pearson Education, 2011) provides in-depth coverage regarding tuning of Java applications. The book outlines the many facets of performance tuning as it summarizes the command-line options that are available and how they can be used to measure and tweak settings so that applications will perform better. This is a complex topic that is covered thoroughly and with focus on recent versions of Java.

3. The Well-Grounded Java Developer

The Well-Grounded Java Developer (Manning, 2012) is a book that is definitely targeted at intermediate and advanced Java developers. As I discussed in my review of The Well-Grounded Java Developer, it helps experienced Java developers come up to speed on some of the latest Java and JVM trends (Java 7, dependency injection, Scala, Groovy, Clojure) while also covering some topics in depth that rarely receive that type of treatment (class loading, performance tuning, concurrency). There are books that specialize in each of these topics, but this is one book that can quickly provide a foundation in all of these advanced topics (and more) in a single book.

2. Java Concurrency in Practice

Like generics, concurrency is another skill that even many advanced Java developers can afford to enhance. Java Concurrency in Practice (Pearson Education, 2006, by Brian Goetz and a host of other Java concurrency luminaries) is the de facto standard among Java books for coverage of writing concurrent applications in Java.

1. Effective Java

Both editions (First Edition and Second Edition) of Effective Java (Joshua Bloch, Pearson Education, Second Edition, 2008) have been outstanding. Christian Beutenmüller made a good point on the DZone syndicated version of Ryan Wang's Top 10 Books for Advanced-level Java Developers: "I would remove Effective Java (since this is one of the first books I recommend to beginners)." Like Beutenmüller, I too recommend Effective Java to new Java developers, but I find myself referring even intermediate and advanced Java developers to Effective Java and refer to it regularly. There are portions of Effective Java that are easily digestible even by those relatively new to Java and then there are portions of that book that I've realized that I don't really appreciate until I have gained knowledge and experience. In many cases, I need realistic experience doing something the wrong way to understand some of the benefits and nuances of the practices outlined in this book. In short, Effective Java is one of the few books I can think of that is particularly appropriate to beginning Java developers, particularly appropriate to intermediate Java developers, and particularly appropriate to advanced Java developers.

Honorable Mention

There are other books that could have made this list and most of us probably have different takes on what are advanced Java books. For me, an "advanced Java developer" is a Java developer with significant depth of knowledge, significant breadth of knowledge, awareness of new and upcoming features of Java, and awareness of tools and products in the Java community that aid the entire Java development lifecycle. Effective Unit Testing and Java Power Tools are two books that are not on advanced subjects, but are books that I think contain information that can help a Java developer move from being a beginner to an intermediate or advanced Java developer. In particular, Effective Unit Testing can help Java developers write better and more efficient unit tests and Java Power Tools helps Java developers increase their breadth of knowledge key open source tools that can be used in all phases of Java development. Beginning Java developers tend not to have the unit testing experience that is contained in Effective Unit Testing and generally lack knowledge of the products available to the Java developer as outlined in Java Power Tools.

Conclusion

It is my belief that it is difficult to write and publish an advanced Java book. Writing an advanced Java books requires the author(s) to have deep understanding of the topic being written about and it is likely that publishers generally sell far more introductory books than advanced books. The barrier to entry seems much higher for writing and publishing advanced Java books as compared to writing and publishing entry-level Java books. Online resources in many ways seem better suited for satisfying advanced Java developers, but the five books I listed in this post buck that trend and provide a level of detailed and thorough information unmatched in the online resources in terms of accessibility and cohesiveness. The books in this list are useful to advanced Java developers, but are probably most useful in helping Java developers to become advanced Java developers.

Monday, September 16, 2013

My Favorite Online Resources for Advanced Java Developers

The ProgramCreek.com blog has recently featured two interesting posts targeted at "advanced" Java developers: Top 10 Books For Advanced Level Java Developers and Top 10 Websites for Advanced Level Java Developers. These posts highlight resources that are especially beneficial to more experienced Java developers. I generally cannot argue with the lists as all the resources listed are useful to Java developers, but if I had to choose my top ten books and top ten online resources for advanced Java developers, there would be a few differences. In this post, I look at some of those differences in my list of best online resources for advanced and intermediate Java developers.

Many of the online resources on my list of best online resources for intermediate and advanced Java developers are the same as listed on the Xiaoran Wang's blog post Top 10 Websites for Advanced Level Java Developers. However, before reading that post, I was not aware of (and so have not had a chance to experience myself) two of them: LeetCode.com and Coursera. Although Wang also has had some interesting posts on ProgramCreek.com, I probably would not have had that site on my list, but it is not surprising he would list his own site on his list. I really like Wikipedia, but rarely use it related to software that I'm developing. Taking out those four sites, my top ten sites for advanced Java developers are as follows.

10. Google News on Java

One easy way to learn about the latest developments in Java (something often of more value to experienced Java developers than those beginning to use Java) is to search Google News for Java.

9. Javit - Reddit/Java

The Javit (Reddit/Java) site does not have as many new articles and blogs referenced as other social media Java-oriented sites like JavaLobby and StackOverflow, but it seems to often link to a very different set of posts and articles than the other sites. I don't check it as often as the others, but I do find an occasional perusal of its links to be worth my time to learn something new about the Java ecosystem.

8. Java Code Geeks

The Java Code Geeks site is a site that includes some original Java-oriented articles and posts in addition to a plethora of syndicated posts created by JCG partners. Several socially-oriented sites are on my list and many of the same articles and posts are featured on multiple of these socially-oriented sites, but each does have some differently featured posts than others.

7. Oracle Technology Network for Java Developers and Java Magazine

Oracle Technology Network (OTN) includes a Java section that features original Java-themed articles, Java news and announcements, references to other Oracle documentation, and links to Java-oriented blogs written by Oracle employees. Some of the employees' blogs that I've found most useful in terms of advanced Java concepts (advanced meaning complex or new) include Joseph D. Darcy's Oracle Weblog, Brian Goetz's Oracle Blog, Mark Reinhold's There's Not A Moment to Lose!, The Java Source, and Geertjan's Blog (which occasionally discusses NetBeans).

Java articles used to have to share space and focus with Oracle database and other products in Oracle Magazine. Today, Java gets its own electronic magazine in Java Magazine, published every two months. The articles in this online magazine are often heavy on newer topics and more advanced topics and so are especially well suited to experienced Java developers.

6. IBM developerWorks

I have found numerous useful articles and presentations for advanced Java developers on IBM developerWorks, which includes a Java emphasis. Authors of articles on this site include Brian Goetz, Elliotte Rusty Harold, Kelvin Lawrence, Ted Neward, and Neal Ford. Speaking of Neal Ford, his IBM developerWorks series on Java.next is a great example of the types of articles that will often appeal to advanced Java developers. IBM developerWorks has published in-depth (in addition to introductory) Java-oriented articles for many years and so now provides a nice mix of both the new and the historically useful.

5. JavaWorld

JavaWorld has been around for a long time and one of the advantages of this is the rich archive of detailed articles written against many different major releases of Java. JavaWorld has evolved somewhat over the years and currently provides a mix of original content with syndicated blog posts and syndicated versions of articles published by sibling publications such as InfoWorld.

4. DZone/JavaLobby

DZone.com is interesting from a general software development perspective and its "Java Zone" JavaLobby.com is interesting from a more Java-specific frame of reference. Both the more general DZone and the more specific JavaLobby link to articles and blogs submitted by "the community." Because the same community votes up or down and can leave comments on the posts, there can be strong community endorsement of good resources, warning to avoid spam or less valuable resources, and comments exchanged that add to the value of the referenced posts. Often, I've found the comments on the DZone syndicated versions of post to be better and more interesting than those of the original article referenced on DZone. As an example of this, the DZone-syndicated version of Top 10 Books for Advanced-level Java Developers has more comments than the original post as of this writing.

3. java.net

The java.net site is another on which I browse headlines on nearly a daily basis during the work week. There are a wide variety of referenced blogs and articles as well as polls on topics of interest to Java developers and editorials on Java-related topics. It's a nice single site to quickly gauge the current events in the world of Java.

2. stackoverflow.com

I doubt there are many Java developers who don't appreciate stackoverflow.com on a regular basis. Although the web in general has changed the way we write, maintain, and debug code, stackoverlow.com has been one of the biggest examples of how things have changed. Software development knowledge was formerly traded purely in conversations, books, articles, and conferences. Then, the advent of the Internet brought forth forums and usergroups for sharing software development knowledge and tactics. The rise of powerful search engines made it much easier to find what one was looking for.

The stackoverflow.com site has made things better than ever for the social collaboration among Java developers, making it easy to locate multiple solutions to multiple problems with community discussion about the merits and disadvantages of each approach. I find this valuable because I rarely need to go to the web for "easy" stuff; I typically go there for strange error messages or little known issues and stackoveflow.com meets that need. The ProgramCreek.com post summarizes it nicely: "Stackoverflow.com is probably the most popular website in the programming world." There is good reason for this.

1. Oracle's Java SE and EE Documentation and OpenJDK Documentation

By Java SE and EE documentation, I mean the following:

The OpenJDK documentation is useful in a similar fashion to how the Oracle Java SE and Java EE documentation is useful. The OpenJDK documentation is particularly useful for learning about new releases of Java such as JDK 8. Significant features of each release are briefly summarized with links to significantly more detail. Examples of this are Project Lambda and Project Jigsaw. Being able to look at source code is illustrative and helps a Java developer become more skilled as well.

Honorable Mention

There are several other useful online resources for improving one's Java abilities even when already fairly experienced in Java. One such example is the Java Specialists Newsletter. Other examples include some blogs that seem to focus on advanced Java topics such as Peter Lawrey's Vanilla #Java.

Conclusion

In many ways, software development is easier than it's ever been with the ability to find useful hints, tips, and answers to questions online with powerful search engines and using social media that helps target answers that tend to be more accurate. These resources have allowed us to expend energy and effort in other creative efforts in software development. In this blog post, I have looked at my top ten online resources for continuing to learn Java even after working with the language and platform for many years. Many forums have questions (and answers) that point newcomers to Java to appropriate beginner materials. I liked Wang's post on online resources for more advanced Java developers and have used this blog post to share my own (slightly different) list of good online resources for more advanced Java developers.

Friday, September 13, 2013

Pre-JavaOne JDK 8 News

With JavaOne 2013 less than two weeks away, it's not surprising that there have been some announcements in recent days regarding JDK 8. In this post, I briefly look at these JDK 8 announcements.

In his blog There’s not a moment to lose!, Oracle's Chief Architect of the Java Platform Group Mark Reinhold recently posted about the JDK 8 Developer Preview. According to Reinhold, the Developer Preview milestone "is intended for broad testing by developers." Reinhold then goes on to highlight that "the principal feature of this release is Project Lambda (JSR 335)" and he describes in one paragraph the impact of lambda expressions on the language. Reinhold specifically mentions some of the "many other new features" of JDK 8 such as the new Date/Time API, Nashorn JavaScript engine, and the removal of HotSpot JVM permanent generation.

On the same day that Reinhold posted "JDK 8 Developer Preview" on his blog (9 September 2013), The Java Tutorials' Weblog featured a new post called "JDK 8 Documentation - Developer Preview Release" and the post "Java Tutorial JDK 8 Early Access Updates" appeared on the same weblog the next day. The latter post states that "new JDK 8 early access documentation" was included with the "updated Java Tutorial" that was part of the "release of JDK 7u40." The post summarizes two major additions to the tutorials: new Data-Time API Trail and bulk data operations lesson.

The JDK 8 Documentation - Developer Preview Release post highlights the "Java Development Kit Release 8 (JDK 8) Early Access Documentation," which it describes as consisting of Developer Guides, The Java Tutorials, and API documentation. Several categories of JDK 8 documentation are described with links to the described documentation: language and library enhancements, security enhancements, tool enhancements, internationalization enhancements, platform and system enhancements, removed features, and more documentation to expect.

Besides the JDK 8 news mentioned in this post, other pre-JavaOne news in recent days has included mention in Java Mission Control (Finally) Released! of Java Mission Control being converged into HotSpot JVM from JRockit as of Java 7u40 (part of Oracle Java SE Advanced). The post Using the Java Discovery Protocol was posted today. It is important to note that, as the Java 7 Update 40 Release Notes state, although "JDK 7u40 includes the first release of Java Mission Control (JMC) that is bundled with the Hotspot JVM," "Java Mission Control (JMC) is a commercial feature available for java users with a commercial License." This is in line with what was discussed at JavaOne 2012.

Monday, September 9, 2013

Book Review: JBoss Weld CDI for Java Platform

JBoss Weld CDI for Java Platform is a relatively short book (approximately 100 "main" pages) that introduces JBoss Weld, which it describes as "the open source reference implementation" of Java Contexts and Dependency Injection. Weld is the reference implementation of Java Specification Request 299 ("Contexts and Dependency Injection for the Java EE platform") and is not limited to use with JBoss Application Server. This post is my review of Packt Publishing's JBoss Weld CDI for Java Platform by Ken Finnigan.

Preface

The Preface of JBoss Weld CDI for Java Platform explains that the book is written for "anyone wanting to understand what CDI 1.0 is and how it can be used to benefit an application's architecture." This Preface also states that the latest version of Weld 1.x is required along with Maven and a "favorite runtime container" (out of JBoss AS7, GlassFish, and Tomcat).

Chapter 1: What is a Bean?

The opening chapter of JBoss Weld CDI for Java Platform provides a brief history of Java "beans" that includes mention of early JavaBeans, Enterprise JavaBeans, and JSF Managed Beans. There are, of course, many more types of "beans" in Java such as JMX Managed Beans (MBeans and MXBeans) and product-specific beans like Spring Framework's beans.

The initial chapter goes on to provide a definition of a CDI bean. Finnigan explains that a CDI bean generally "needs a non-private constructor with no parameters" to be "proxied by the container" before discussing use of the @Inject annotation for classes without a no-argument public constructor. There is a typo here as the text reads, "It is also possible for a bean to be proxied by the container if it does not have a constructor with any parameters," but I think the text should read, "It is also possible for a bean to be proxied by the container if it does not have a constructor without parameters" or "It is also possible for a bean to be proxied by the container if it does not have a constructor no parameters."

Chapter 1 of JBoss Weld CDI for Java Platform introduces several other annotations besides @Inject; these include @Dependent, @RequestScoped, @ApplicationScoped, @SessionScoped, @ConversationScoped, and @Alternative. The chapter includes coverage of the beans.xml file and discusses where it should be placed and what it should contain.

The first chapter continues its introduction to CDI beans by quoting the CDI specification of the characteristics required of a CDI bean and then focuses on each characteristic (bean types, qualifiers, scope, interceptor bindings, bean implementation, and optional bean expression language [EL]). These introductions to the characteristics of a CDI bean introduce more annotations such as @Typed, @Qualifier, and @Named.

The packed ten-page first chapter continues with coverage of CDI's @ManagedBean (not to be confused with JSF's @ManagedBean) and @Produces (on methods and fields).

Chapter 2: Dependency Injection and Lookup

The second chapter of JBoss Weld CDI for Java Platform begins with a deeper look at dependency injection using Weld. Finnigan describes the ability to inject dependencies at class level (via no-arguments constructor or constructor annotated with @Inject), at get/set method level, or at field level. I was happy to see that he specifically mentions constructor setting and field level setting of injection points as preferable to method level setting to support creation of immutable objects. (I think the importance and value of immutability (when possible) in Java objects is still under-appreciated.)

The second chapter provides more focus on qualifiers (including @Any and @Default annotations), alternatives, and client proxies, and injection point metadata.

I like that Finnigan talks about some likely errors (including error message output) that can occur when configuration problems exist. I wish more introductory books did this, focusing on things that often go wrong rather than simply covering the happy path of using the framework or tool being introduced. Finnigan includes a section in this chapter called "Resolving Weld deployment errors" that lists the common types of errors that can occur with Weld deployments (unsatisfied dependencies and ambiguous dependencies) and then lists multiple ways to resolve each.

Chapter 3: Deploying JBoss Weld

The third chapter of JBoss Weld CDI for Java Platform covers "installation of JBoss Weld into Java EE 6 and Servlet containers." Finnigan points out that "all Java EE 6 containers will come with an implementation of CDI preinstalled," but also makes the point that it's worth knowing how to install or deploy Weld because the version bundled with the container may be insufficient. The chapter talks about how to download Weld and mentions that the current version as of the book's writing was 1.1.10 (at the time of this blog post's writing, Weld 1.2 beta and Weld 2.0 are available for download).

Chapter 3 concludes with a useful discussion on upgrading of Weld versions within three containers: JBoss AS 7 (7.1.1) with bundled Weld 1.1.5Final, GlassFish 3 (3.1.2.2) with bundled Weld 1.1.8Final, and Apache Tomcat 7.0.35 (no bundled Weld implementation because Tomcat is a web servlet implementation).

Chapter 4: Scopes and Contexts

JBoss Weld CDI for Java Platform's fourth chapter delves deeper into the concepts of scopes and contexts introduced earlier in the first chapter. This fourth chapter introduces the concepts of normal and pseudo scopes. Finnigan explains that the differentiating factor between normal scope and pseudo scope is whether a client proxy is required or not. The chapter provides a relatively large section on the built-in scopes introduced earlier and describes the underlying respective lifecycles: request context, session context, application context, and conversation context. I liked that Finnigan wanrns about conversation scope in CDI 1.0 being specific to JSF, but mentioning that CDI 1.1 (JSR 346) is expected to make conversation scope more generally available.

The majority of Chapter 4 is spent on normal, built-in scopes and their associated contexts. In particular, a significant portion of the chapter is dedicated to coverage of using the conversational scope with JSF. The chapter, however, does briefly describe pseudo scopes and concludes with an example of writing custom scope and context.

Chapter 5: Producers

The fifth chapter in JBoss Weld CDI for Java Platform provides greater focus on another topic introduced in the first chapter: producers with @Produces and @Disposes. This chapter's coverage includes some more highly useful side notes with special emphasis that discuss the use of @New, but also mention that @New is deprecated in CDI 1.1 in favor of @Dependent at the injection point.

Chapter 6: Interceptors and Decorators

Chapter 6 of JBoss Weld CDI for Java Platform introduces interceptors and decorators and differentiates them, "Interceptors are perfect for separating concerns that are orthogonal to our application ... Decorators are well suited for solving business problems that apply to a hierarchy of classes of the same type."

This chapter provides relatively in-depth coverage of created interceptors and decorators. I like the fact that the examples, especially the interceptors examples, include some complicating issues to take the examples past "Hello World" status and to be more reflective of what one might do with these constructs.

Chapter 7: Events

The seventh chapter of JBoss Weld CDI for Java Platform covers "events within CDI" including "how they are fired" (javax.enterprise.event.Event.fire), "how we listen for new events" (@Observes), "what we can use as an event payload" (concrete Java classes), and "how we can narrow what events we can listen to and fire" (event qualifiers and conditional observers).

Chapter 8: Writing a Portable Extension

Chapter 8 is the last chapter of JBoss Weld CDI for Java Platform that focuses on detailed coverage of Weld concepts in an purely introductory fashion because Chapter 9 and Chapter 10 focus on an example book store application. This chapter's focus is use of CDI-exposed Service Provider Interfaces (SPIs) that allow extension and customization of CDI. The chapter outlines the development of portable CDI extensions by implementing javax.enterprise.inject.spi.Extension and registering the extension in META-INF/services/javax.enterprise.inject.spi.Extension. The chapter discusses the "core" role of BeanManager in allowing extensions to access the CDI lifecycle. Chapter 8 also mentions Apache DeltaSpike, a product which I had never heard of, but which its homepage advertises as "a number of portable CDI extensions that provide useful features for Java application developers."

Chapter 9: Book Store – CDI Services

JBoss Weld CDI for Java Platform's ninth chapter is the first of two chapters that use an online book store application as a CDI/Weld example intended to "provide a more indicative picture of how (Weld CDI) can be utilized," to "cover some of the CDI usage patterns that can be beneficial," and to "provide clear examples of topics that we have discussed in the previous chapters." Chapter 9 introduces the example application and demonstrates building its "back end" (services, interceptors, and events portions).

Chapter 10: Book Store – User Interfaces

The tenth and final chapter continues the example online bookstore application started in Chapter 9. This chapter focuses on the "front end" of the example application and demonstrates "how CDI services can be reused to create two distinct user interfaces." The two technologies used for the interfaces are AngularJS and JSF2/Rich Faces. In the book's example application, REST is used for communication between the user interfaces and the services.

Strengths
  • General CDI Specification (not just Weld) Resource - Although the book title and some of its content suggest focus on the CDI implementation Weld, the vast majority of the book is likely applicable to most common implementations of CDI (Chapter 3 being about the only significant exception that is highly Weld-specific rather than CDI-general). I find it often to be the case that books on reference implementations are good sources of information on the specification being implemented and that is definitely the case with JBoss Weld CDI for Java Platform; it can serve as simply "CDI for Java Platform."
  • Forward-looking - Technology books, especially those focused on new implementations of ongoing specifications, always come with great risk of being outdated quickly. Finnigan's mention of CDI 1.1 in several parts of the book helps to mitigate this risk at least a bit.
  • Appropriate Level of Detail - This is not a very lengthy book, but its length feels appropriate. There is nice introductory discussion along with discussion on some things to do and not do with CDI/Weld. There are several code examples, but most are short and easy to follow. The lengthy and more difficult to follow examples are reserved for the final two chapters on the sample application.
Conclusion

I really enjoyed JBoss Weld CDI for Java Platform and recommend it to anyone interested in learning about Java EE CDI in general or the Weld implementation of CDI in particular. Other than a few typos such as the one I mentioned in this post, the text is generally well-written. I particularly like the text's mixing of introductory material with forward-looking caveat statements and discussion of why certain practices are beneficial or detrimental in different circumstances.

Monday, September 2, 2013

Better JUnit-based Unit Tests with NetBeans 7.4 beta Hints

In my last post, I wrote about hints provided in NetBeans 7.4 beta that improve a developer's ability to avoid nasty runtime issues with Java exception handling. In this post, I look at how two more hints provided by NetBeans 7.4 beta can be used to make unit tests more correct and more clear during unit test execution. These are the "Inconvertible parameters of Assert.assertEquals" and "Incorrect order of parameters of Assert.assertEquals" hints.

As far as I can tell from anecdotal evidence and from talking to other Java developers, JUnit remains the most widely used unit testing framework in the Java environment. Most of these JUnit users are intimately familiar with JUnit's Assert class and its many overloaded assertEquals methods. NetBeans 7.4 beta now provides two hints to make it easier to use these assertEquals methods appropriately.

Although many of the Assert.assertEquals() methods have very specific data types for the "expected" and "actual" parameters to be asserted as equal, there is a version that accepts two Objects and this means two parameters of different types that cannot possibly be considered "equal" can still be passed to that method. There is no way for the compiler to prevent that, but NetBeans 7.4 beta includes the "Inconvertible parameters of Assert.assertEquals" hint to address that particular case. Without such a hint, one is more likely to not realize the error of his or her ways until he or she runs the JUnit test and sees the failed assertion.

One of the most common issues I've run into with JUnit (and one of the reasons I love Hamcrest's fluent API) is that I just cannot seem to remember with confidence which order the parameters to the assertEquals methods are. I have a 50/50 chance of being correct by guessing. Modern Java IDEs such as NetBeans help greatly when writing new JUnit code because their method completion features will indicate that the "expected" parameter is specified first and the "actual" parameter is specified second. More commonly, this is a problem when reading code rather than when writing it because there is no method completion helping me read the code. NetBeans 7.4 beta addresses this by highlighting the situation in which I have mixed up the parameters' order via the "Incorrect order of parameters of Assert.assertEquals" hint. With that hint enabled (which it is by default), I can quickly recognize out-of-order parameters prior to runtime and even without method completion.

Both of the hints discussed above can be demonstrated in a very simple unit test class.

Portion of CalculatorTest.java
/**
 * Test Calculator.sum(int ...).
 */
@Test
public void TestSumIntegers()
{
   final Calculator calculator = new Calculator();
   Assert.assertEquals(calculator.add(1, 2, 3, 4, 5), 15);
   Assert.assertEquals("15", calculator.add(1, 2, 3, 4, 5));
}

The code the above unit test method is testing is not important for this discussion. Rather, the focus is on the use of Assert.assertEquals in two cases. Both cases as shown above are incorrect and force demonstration of the two previously discussed NetBeans hints. The first attempt at asserting two objects are equal places the parameters in the wrong order. The "expected" value (hard-coded 15) should be listed first followed by the "actual" value calculated by the method under test. The second attempt at asserting two objects are equal will always fail because the types don't match: the first parameter is a String and the second parameter is an integer. In both of these cases, the unit test code compiles without complaint. However, both assertions will ALWAYS fail when running the unit tests. In fact, these tests results may inadvertently be interpreted as problems with the code being tested until someone looks at the test failures in greater depth.

The next two screen snapshots demonstrate NetBeans 7.4 beta flagging both problematic unit testing assertion statements.

There is one caveat to note regarding the "Incorrect order of parameters of Assert.assertEquals" hint. It works well when the assertion statement is like the one shown in my example: a hard-coded expected value is provided as the "actual" value along with an obviously calculated value as the "expected" value. The next screen snapshot illustrates this point; only the statement I earlier showed is flagged by the hint and other ways of comparing actual to expected are not flagged, even when the order is incorrect.

The last shown screen snapshot demonstrates that the NetBeans hint is only able to detect an incorrect order of assertEquals parameters (should be expected before actual rather than actual before expected) in the case where those values are directly accessed in the statement (the actual calculation is performed for the first [expected] parameter and the expected hard-coded value is provided for the second [actual] parameter).

The two hints covered in this blog post make it easier to detect problems with the frequently used JUnit Assert.assertEquals methods that might not be detected until analysis of unit test run results without the hints. Although the two issues these hints warn developers about are typically fairly easy to detect and fix, detecting and fixing these problems is still more difficult and time-consuming than having the NetBeans IDE tell you they are wrong before you even run the test.