Friday, January 1, 2010

Java trick: anonymous objects for single value computation and lazy evaluation

Instead of

int v; {
line1;
line2;
v = result;
}

I sometimes prefer

int v = new Object() {
int compute()
line1;
line2;
return result;
}
}.compute();

This is not sintactic shugar -- it adds 3 more lines of code (obj/method decl and call). A bit of clearity comes because we can see that the block initializes the variable. Additionally, this coding is the only one that is possible in some situations, like

var x = c ? a : multiline_computation();

Without lazy evaluation we would break the convenience of ternary operator -- we would have to declare/implement the multiline_computation() somewhere where we do not use it. Insn't it great to encapsulate everything into a narrowest context both in terms of visibility and appropriate invocation?

var x = c ? a : new Object(){}.compute()

No comments: