• Home
  • Events
  • About
  • Clearer Unit Tests: Assert, Guard, and Throw

    September 27th, 2010

    I hate the book “xUnit Test Patterns” for being over 800 pages long. I am convinced a good editor can turn any 800 page book into a 700 pager with the exact same content… that includes you Leo Tolstoy! The problem is that xUnit Patterns is still the definitive reference to test concepts and implementation. There is no better book on testing available, but the sheer weight and size the book means few have actually read it. Well I have, and I highlighted the damn thing just to prove it. In this post you’ll find 3 techniques to improve test clarity that, in my opinion, are underutilized in the development world today.

    Custom Assertion Methods
    I commonly see assertions repeated throughout a test case in sets. For instance, my current system deals in User objects, and you can see the same 3 lines of code sprinkled throughout a test case:

    This is a form of test code duplication. It plain English, you want to say “make sure that the user we got back is the same one we expect”. This points to two concerns: an assertion (“make sure”) and equality (“the same”). It is temping to refactor using Extract Method, but this is a poor solution:

    This isn’t bad, it just isn’t good. The test reads better, but the parameter list of the custom assertEquals is quite busy. It sort of half encapsulates equality. Equality is defined in the assertion method, but the attributes that contribute to equality are defined in at the place where assertEquals is invoked. A better solution is proper, canonical Assertion Method: two parameters and static.

    I follow this pattern because it keeps my options open. The assertEquals method is static. When I need to move it to my AssertionUtils or CommonAssertions class, then it is just a keystroke away (Ctrl+Alt+V or F6). Also it is common to construct a factory method for a canonical, or expected user. Having assertEquals written with a (User, User) parameter list means that you can hide the expected data behind a factory method and not have it clutter up your test. For me, a custom assertion method is the cleanest solution. The test code is readable because it captures the equality concern without showing the equality implementation. Hey, it’s an abstraction!

    Guard Assertion
    In tests, decisions are the enemy of clarity. If you read a test method, any decision you come across is a detail that can clutter and obfuscate the meaning of the test. Mock object setup is classic clutter: “when x is called then return y” is a setup step that seldomly is a meaningful part of the test case. But assertions can contain decisions as well. Consider this test:

    On first glance it looks complicated. This is how we sometimes write production code… be defensive and always guard against null pointers and illegal state. But remember, tests are different. What do you want your test to do when there is a null pointer? Blow up with a null pointer exception, of course! Forget these fail() methods and just write it so it blows up:

    It is shorter, and less to take in. But there are less decisions in the test as well. No deciding on sizes and nullability. If the user list of user is null then it blows up with a stack trace. Which is what you want in a test! The conversion from conditional statements to assertions is called a Guard Assertion. Use them to clarify your tests by eliminating unneeded conditionals and decisions.

    Throw Everything
    I blogged a while back about testing exceptions. Now it is time to say don’t test exceptions. Consider this approaches to handling exceptions in test methods:

    This happens with fancy IDEs. A quick shortcut adds the exception to the method signature. But what’s the point? There is absolutely no reason a test shouldn’t just throw Exception. It is simpler, you can add it to your test method template, you never have to look at it again, and you never have to think about it. Throw Exception. It’s the simplest thing you can do. Another common occurrence is to see this type of exception code in a test method:

    Yes, it is important to fail the test when an exception occurs. But do you know what happens when fail executes? It throws an unchecked exception. This code suppresses the cause of the exception only to throw a different one. The try catch block is a form of an unneeded decision in your test case. It can be completely eliminated by just throwing Exception in the test method. This way your stack trace points to where the problem occurred, not where it was handled. Both these examples are simplified into the same result:

    That’s it: 3 tips for clearer test code. And in far less than 800+ pages!

    Share and Enjoy: These icons link to social bookmarking sites where readers can share and discover new web pages.
    • email
    • Print
    • Twitter
    • LinkedIn
    • XING
    • Facebook
    • Google Bookmarks

    JavaOne 2010 Final Remarks

    September 25th, 2010

    JavaOne 2010 is already history and allow me to make some final remarks. This years’s JavaOne marks the biggest change this conference has ever seen. Replacing the familiar Sun logo by the Oracle logo (well almost – the Audi TT in the Java Frontier demo session still had a Sun sticker on it) was just the least of changes. Java now seems to be just one technology in Oracle’s portfolio and not the pivotal technology as with Sun. It was a pretty sobering experience how the Java community pales next to the Oracle Develop conference. And the fact that the JavaOne sessions were “banned” from the Moscone center where the Oracle Develop conference took place emphasized this even more. Granted, it is far from easy to keep the enthusiasm rolling with a technology that is more than 15 years old. Sun did a far better job on this in the previous years, though.

    Whereas the sales part was fairly bad the content is still top-notch. I enjoyed quite many good technical sessions even with the conference venue being a drag (most rooms were not really suited to host a conference session). Spreading the conference across three hotels around Union Square had only one advantage: sessions were only one hour long since people took much longer to move to the next session and hence, speakers were forced to focus more. I also missed the JavaOne slide templates. Sun used to keep a pretty tight leash on how slides looked like. This year, most slides were just alphabet soups.

    The major topics of this year’s JavaOne were JavaFX on the client side (despite JavaFX Script’s demise) and the cloud and REST on the server side. I keep wondering whether JavaFX will really conquer the desktop, though. This will be a tough uphill battle, but Oracle tends to be more persistent (or stubborn) than Sun used to be. Having deep pockets certainly helps with this. The prominent absentees were portlets, Java ME, and Google. I haven’t seen a single session about portlets in the conference guide. For Java ME, they offered quite some sessions, but it got barely covered in the keynotes. The mobile world now turns around iOS and Android, JavaME seems to have fallen by the wayside. Last but not least, Google withdrew from the conference at short notice due to the legal battle started by Oracle. I certainly missed them because the Google sessions were always among the best technical sessions at JavaOne.

    It was also interesting to see what kind of devices the attendees were using. iPads seem to be very popular with Java developers (despite the fact that the iPad does not run Java!).

    My bottom line is that Java as a technology is well entrenched in the developer world and here to stay. I am not so sure about JavaOne. Oracle has quite some homework to do in this area.

    Share and Enjoy: These icons link to social bookmarking sites where readers can share and discover new web pages.
    • email
    • Print
    • Twitter
    • LinkedIn
    • XING
    • Facebook
    • Google Bookmarks

    Beautiful Java Enums

    September 24th, 2010

    File under “It’s never too late to blog about Java 5 features” and “you wrote 1000 words on what?”.

    Way back before Java 5 I fell in love with the Type Safe Enum pattern described in Martin Fowler’s Refactoring. You know the one, where an instance of a class has members of itself as public static fields. It was so clever (not always a compliment) and I applied it everywhere I could. Fowler’s example dealt with blood types:

    For the most part you had a finite amount of BloodTypes in your system and you could use == for comparisons, which was sort of guaranteed by the private constructor. Kinda sorta in that serialization, class loader, or reflection shenanigans could break this. But safe enough anyway. It was such a good idea that Java 5 created a new keyword called “enum” and built the pattern into the language. Java developers reveled in the newfound productivity of having to produce about 130 less bytes of source code.

    Java enum types came with some guarantees about equality and instances but honestly I can’t remember the specifics and am too lazy to go look them up. This new way was seen as a big improvement because the idea a “complexity budget” hadn’t been invented yet and there were no vocal bloggers clamoring for a simpler, more consistent Java. I wonder today if we really needed this new introduction to the type system, but that is a post for another day. I liked enums and still do. They were meant to replace integer based abominations like this, which would make an API horrible to work with (I’m looking at you Swing):

    And don’t even get me started about bitmasking these damn values. Ugh, horror. Few developers knew about the Type Safe Enum Pattern, so it was the right call to back it into the language and move people away from integer based APIs.

    Back to Java 5 enums. There are a few API methods around the Enum type which you should not use. First is ordinal() which gives you the integer based position in which your enum instance was declared. TYPE_A is 0 and TYPE_B is 1. The Javadoc gives a nice little warning: “Most programmers will have no use for this method.” But apparently enough people did use it that Joshua Bloch’s Effective Java 2nd Edition felt the need to expand this sentence to about 3 pages. This integer is subject to change without warning! My current IDE setup autoformats code and alphabetizes these darn things. Writing code that depends on the order of the enum declaration is bad. Don’t do it unless you are writing something like EnumSet or EnumMap.

    Another method to not use is name(), which gives you the type name, like “TYPE_A” or “TYPE_B” (which incidentally is the same thing toString() gives you). This is handy but the Javadoc gives a not-very-specific warning: “Most programmers should use the toString() method in preference to this one, as the toString method may return a more user-friendly name.” If you use name() then you are dependent on the actual declaration name of the enum entry. Future refactoring may break your system and you’ll be stuck not able to change enum names if you want to. Instead rely on toString if you really need to. That way your implementation (the name of your enum) and the public API can change independently of one another. Sure, you may never need it, but it takes very little effort to use toString instead, so just do it.

    Of course, your system shouldn’t rely on toString() either, unless you are rendering the enum into a log file or user interface. Instead, I like to add a String name to all of my enums:

    Again, this is a small change that gives you future flexibility. If the String description or name of your enum is important than model it. Yeah, you might not need it, and Java makes it kinda verbose, but a dependency on toString() is both a bad idea and a simple thing to get rid of, so just do it.

    The bigger problem with name() is that it is often used in conjunction with valueOf(Class, String) which allows you to lookup an Enum entry based on the string representation. I see this often in generated code, in particular around the JDK wsimport tool to create objects from a WSDL. If you have code like this, using the native enum name(), valueOf(), and XML schema definitions for enumerated values, then you will always have to change all three definitions at once: The web service .xsd, the clients, and the generated code. Having a single change affect multiple source files is an antipattern called “Shotgun Surgery“. Hopefully you have control over all your clients, but if you have a public web service then you’re going to be stuck with your names for quite a while. A simple way to make your enums flexible and future-proof is to keep your own map of Strings to enum instances and provide a translation method instead of relying on valueOf:

    The static block just stuffs all the enum values into a lookup map based on their name. Then a fromString(String) method can be written that hands you back an enum instance for a String. You have flexibility on whether to return null or throw an exception when the String is unrecognized.

    The value here is complete control over the names of elements. Say you want to recognize “A_POSITIVE” and “A_NEGATIVE” as TYPE_A… well now you can. Or perhaps you want it case insensitive… just change the implementation. The Enum.valueOf method is static, and as far as I know there is not way to change it! About the only thing you can override in Enum is toString(). This whole thing is a pretty easy pattern to write and it buys you quite a bit of future flexibility, so just do it.

    Is this a little verbose? Sure. Are you sure you need this future flexibility? Not completely. Will you be screwed later if you don’t write enums this way? Quite possibly. Is it worthwhile? I think so, and hopefully I’ve convinced you as well.

    Got Java problems? Canoo can help. Email info@canoo.com to learn more about what we can do for your project. You’ll be glad you did.

    Share and Enjoy: These icons link to social bookmarking sites where readers can share and discover new web pages.
    • email
    • Print
    • Twitter
    • LinkedIn
    • XING
    • Facebook
    • Google Bookmarks

    JavaOne 2010 Day Four

    September 24th, 2010

    It’s already Thursday and JavaOne 2010 starts it’s last day. By tradition, the last day of the conference starts with a keynote mostly dedicated to cool Java technology demos and Oracle continued with this tradition. The keynote intro was presented by Ray Kurzweil, who is an author, inventor and futurist. Among others, he made major contributions in OCR and text-to-speech synthesis. His talk focused on exponential growth in information technology, which he illustrated with numerous examples. He claimed that everytime exponential growth reaches its limits a paradigm shift will open the ground for new exponential growth. For example, in the early days of computing vacuum tubes were shrunk exponentially. When this was not possible anymore the shift to the transistor opened the opportunity for exponential growth for quite many years.

    From the demos only one was really remarkable and worth mentioning: Livescribe, a Java-powered pen which records what you are writing and saying. I saw the first demo of Livescribe two years ago at JavaOne and still it impressed me again. Imagine that the pen application tells you how to draw the “user interface” on paper which then allows you to use the application.

    Nevertheless, I missed the enthusiasm of the previous Java technology demo keynotes (not to mention the T-Shirt hurling contest). And I have never seen such a small keynote audience at a JavaOne.

    “The Merging Point of Android and Swing” was my first technical session. It was given by the David Qiao, lead developer of JIDE, a company well known for its Java and Swing components. He had a look at what Android provides for user interface construction and how some of these ideas can be applied to Swing. The talk focused on the areas of resources and themeing. In both cases he demonstrated libraries he has been developing to make life easier for Swing developers. For resources the Android approach cannot really be ported to Swing without changing the API and his solution therefore looked a bit awkward. On the other hand, he showed a nice solution how a theme can be declaratively adapted. Last but not least I learned that colors have to be localized as well, e.g. in Western cultures rising stock prices are emphasized in green, falling stock prices in red; in China it is the other way round!

    The “DSL vs. Library API Shootout” featured Rich Unger (the DSL guy) vs. Jaroslav Tulach (the library API guy). The result of the shootout which luckily both survived was: use an external DSL when your users are more domain experts and less Java developers, otherwise go for a library (or internal DSL) approach. Jaroslav also gave a nice demo how you can use the annotation processor together with IDE facilities to provide much nicer internal DSL support in Java. Both speakers also emphasized that evolution is challenging regardless whether for a DSL or an API.

    The topic of “What’s Happening with My Application?: Java Virtual Machine Monitoring Tool” was the project “Palantir”, a JVM monitoring tool being developed at Oracle. Very impressive stuff: it is based on DTrace which is a non-immersive technique for tracing on the kernel level. It is available on Solaris, Mac OS X and some Linux derivatives. Since Java 6 DTrace can also be used for the JVM. Palantir comprises a set of DTrace scripts tailored to the needs of investigating Java performance problems and a powerful tool for visualizing the trace log. The tracing is accurate since it is not sampling based as with typical profilers and not only shows JVM events but also events of the hosting operating system. They demonstrated a show case where Oracle had a massive performance problem which engineers had been trying to fix for quite some time. With Palantir the problem was identified in about 30 min without any access to the source code. The engineers guessed that it would have taken them at least another month to pinpoint the culprit.

    My last JavaOne session was “Developing Rich Modular Clients with Java, JavaFX, and OSGI Technology”. The speaker is working for Oracle where he and his team developed a bridge between JavaFX and OSGi to create modular JavaFX clients. They used Felix as the OSGi container, defined the OSGi service interface in Java and the service implementation is developed in JavaFX script. Nice but with JavaFX Script on the way out this is kind of pointless. The poor guy learned about JavaFX Script’s demise only on Monday when it was officially announced by Oracle.

    Share and Enjoy: These icons link to social bookmarking sites where readers can share and discover new web pages.
    • email
    • Print
    • Twitter
    • LinkedIn
    • XING
    • Facebook
    • Google Bookmarks

    JavaOne 2010 Day Three

    September 23rd, 2010

    My third day of JavaOne 2010 started with “Using Context and Dependency Injection (CDI) in the Java EE 6 Ecosystem”. This excellent talk gave a superb overview of many aspects of CDI. CDI is the JSR-299 (formerly known as WebBeans) which substantially enhances JSR-330. JSR-330 can also be used on Java SE whereas JSR-299 is for Java EE only. Arun Gupta, who is an incredibly fast speaker, started with the basic guiding principles of CDI, such as type safe dependency injection or strong typing and loose coupling. He then covered all the different aspects of CDI, e.g. producer & disposer, interceptors, alternatives or stereotypes. Small code examples demonstrated the application of CDI in different scenarios for JSF, JPA and JAX-RS. He promised to publish the slides on this blog and its certainly worthwile to get them.

    Next up was Paul Marray with “Too Big to Fail: Top Tips for Massive, Mission-Critical Enterprise Applications”. The title was slightly misleading. I mostly expected tips on the architecture and design level but he focused on VM configurations, profiling and low-level coding. Nevertheless, a great talk and highly recommendable. Most tips were really simple but with more than great results, e.g. using compressed pointers on 64 bit VMs can get up to 30% improvement. Or, if you need to cache lots of read-only data and share them among several VMs on the same machine have a look at the DirectMappedByteBuffer class. For me the most surprising tip was how the identity hashcode can really deteriorate your garbage collection both in terms of memory size and execution time. The identity hashcode is for example created when you are serializing objects. Once created you cannot get rid of it anymore, it becomes part of the object as long as it lives and as a consequence the garbage collector needs more space and time to execute. BTW, many years ago Paul Murray used to work on a product called SoftPC, the first Mac VM for running Windows on a PowerPC. No wonder he is a low-level guy.

    The talk “Creating Great-Looking Java Apps for Mac OS X Without Learning Objective-C” was slightly disappointing. The speaker introduced the Xito Dazzle library which provides typical Mac UI components such as source list or sheet dialogs. To me, this library looked inferior to MacWidgets and beyond that I didn’t learn anything new about platform-specific Java UI development. I liked one quote, though. When talking about user interface design being a craft not appreciated by managers he said “Managers who call me a resource don’t consider my work as a craft”.

    Another talk by SpringSource was next: “Standard DI with @Inject and JSR-330”. JSR-330 was one of the fastest JSRs ever. No wonder, since it is very small. The JAR-file is only about 2.5 kB and contains a mere 5 annotations (Inject, Named, Qualifier, Scope and Singleton) and one interface (Provider). The speaker went through each of the annotations and demonstrated how the JSR-330 can be used with Google Guice (which is the reference implementation) and Spring 3.0. Apart from common applications he also discussed corner cases and there was a lively discussion after the talk as well. Bottom line: excellent talk given by a savvy speaker.

    My last session was “Developing Beyond the Component Libraries”, which was about how to customize Swing components, develop Swing components from scratch or customizing a Swing L&F. Each of these topics would have deserved a session of their own and therefore the speaker really had to rush through his many slides. The basic concepts of how the Swing component library separates the functionality of a component from its appearance were conveyed pretty well. The demos, however, were not that convincing. Maybe I am spoiled by the famous Filthy Rich Client sessions of previous JavaOnes.

    Share and Enjoy: These icons link to social bookmarking sites where readers can share and discover new web pages.
    • email
    • Print
    • Twitter
    • LinkedIn
    • XING
    • Facebook
    • Google Bookmarks

    css.php