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
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.
Bar getBarOfThing(Thing thing) {
Bar bar = null;
if (thing != null) {
Foo foo = thing.getFoo();
if (foo != null) {
bar = foo.getBar()
}
}
return bar;
}
Now imagine that
foo = new Function<Thing,Foo>() {and
public Foo apply(Thing from) {
return from.getFoo();
}
}
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 =Which I can safely apply to any Thing, including null
FunctionChain.<Thing>self().function(foo).function(bar);
assertTrue(chain.applyTo(null) == null);
No comments:
Post a Comment