Last week I started using JAXB to construct and consume XAdES digital signatures. One of the aspects that I immediately disliked was the way to build the object trees, using the classes generated by the binding compiler (XJC). Each of these classes has a parameterless constructor and a set of setter and getter methods to assign and retrieve each of the properties. Unfortunately the setter methods have void as the return type, meaning that an object initialization requires multiple statements. When building a deeply nested hierarchy, this implies code like the one showed below, where the tree is built in reverse order (from leafs to root).
I find this code very unpleasant to write, namely when I’m familiar with better idioms, so I immediately started thinking in a way to solve this.
Fortunately, I found the XJC Fluent API Plugin, which extends the classes generated by the binding compiler with extra methods called “withXXX”. These methods are similar to the setter methods with the important difference that they return the instance on which they were called, allowing for method chaining. Using this, the above initialization code becomes
Notice that the code structure now follows the element structure (from root to leafs). This makes it easier to read and also to write, since the IDE’s auto-completion feature can be used to “guide” the method chaining.
Some remarks regarding this plugin: