Tom McAdam

expecting the unexpected

Warning: this is a bit of a rant post.

Expecting the unexpected is good practice in a bunch of situations, such as planning for an Arctic solo trek or a complex release, but when I’m using an API or a library it’s the last thing I should need to do.

We were recently looking at a small bug in outputting data from Atlas, where the end of availability date for a location was always being output as “now”. Weird. The effect was that, instead of saying that a particular piece of on-demand content was available in perpetuity, we were actually saying that it is about to be no longer be. It took only a couple of minutes to hunt down, and about as many again to write a test and to fix, but was frustrating.

It turns out that DateTimeFormatter print method in the Joda library has quite a surprising interpretation of nulls. Rather than, y’know, throwing a NullPointerException when asking to format a null reference, it decides to treat null as now. Interesting. Given that, and the fact that in Atlas we represent “no end date” with a null, we had a problem. Now, the Joda behaviour is documented:

Prints a ReadableInstant to a String.

This method will use the override zone and the override chronololgy [sic] if they are set. Otherwise it will use the chronology and zone of the instant.

Parameters: instant – instant to format, null means now

Returns: the printed result

But hey, that’s somewhat beside the point. It’s not exactly how one would expect the print method to behave if passed a null reference. Remember, folks, when you’re writing an API or some code others are going to use, put yourself in their shoes: how would you expect it to work? Let’s all do our part in keeping that astonishment to a minimum.

If you enjoyed the read, drop us a comment below or share the article, follow us on Twitter or subscribe to our #MetaBeers newsletter. Before you go, grab a PDF of the article, and let us know if it’s time we worked together.

blog comments powered by Disqus