On one of my current projects, the system receives a web request from a consumer, makes further requests to upstream services and collates a response. For the sake of illustration, let’s say that one of these upstream systems was IMDB and its response looked like this:
Let’s assume that we want to verify that our system handles the above XML correctly. Because we want to avoid external dependencies in our integration tests, we fake IMDB out and build the fake’s response inline within the test:
(here film() is just a method that invokes new FilmBuilder())
We need some code which satisfies this API and produces the appropriate XML.
The Java Version
The original, (Java) implementation looks like this:
This satisfies the requirements but is very meat and two veg (and ain’t really much of a looker). Perhaps we can improve on it.
The Scala port of the FilmBuilder looks like this:
Interesting features and gotchas to mention:
Your XML needs to be valid markup. Your IDE’s compiler will be an angry red until you put that closing tag in. This is a nice contrast to the Java solution’s string building approach, which is very susceptible to leaving a dangling tag open somewhere accidentally.
You can use conditionals in your template. This is particularly useful when you have optional tags in your XML.
Collections get flattened correctly inline (which is pretty awesome). This means that you only really have to generate an enumeration of XML nodes and let Scala do the rest.
Inline strings get helpfully escaped. This does mean though that if you have an inline string <tag>...</tag>, it will in fact be rendered as & lt;tag & gt;...& lt;tag & gt;, which may not be exactly what you wanted. To prevent this from happening, you need to wrap your string in an Unparsed (I’ve done this above for the actor tag).
I like how you can recognise the XML structure in the Scala version. This isn’t really possible (with all that noise) in the Java variant.