Wednesday, November 7, 2007

Null-safe access to properties

First I am going to show a nice side-effect of using properties with google-collections interface Function. Like many others I am annoyed to write code of the style


Bar getBarOfThing(Thing thing) {
Bar bar = null;
if (thing != null) {
Foo foo = thing.getFoo();
if (foo != null) {
bar = foo.getBar()
}
}
return bar;
}
All the null checks make it unreadable. And heaven forbid I forget one null test... BOOM! NPE! It's much nicer in SQL, for example, where everything's a bag, no results - no problem, join it with whatever you want, you'll just get an empty bag.

Now imagine that
foo = new Function<Thing,Foo>() {
public Foo apply(Thing from) {
return from.getFoo();
}
}
and
bar = Function<Foo,Bar>() {
public Bar apply(Foo from) {
return from.getBar();
}
}

Luckily google-collections have defined a @Nullable annotation and I am going to use it to differentiate between functions that can gracefully handle null (e.g. return some default value) and the ones that don't. Now I'm going to define a FunctionChain class, that provides me a fluent interface to chain the functions:
  FunctionChain<Thing,Bar> chain =
FunctionChain.<Thing>self().function(foo).function(bar);
Which I can safely apply to any Thing, including null
  assertTrue(chain.applyTo(null) == null);

No comments: