java boilerplate

Thursday, December 01, 2005

null-checking reference operator.

An oft-recurring java situation: You intend to return null if something is not found, and some sort of result otherwise. Unfortunately, to get to the 'result', you need to make one or even more references (the dot ('.') operator). At any step, the result could be null. Writing this hypothetical method as a one-liner does not work, as it would potentially throw NullPointerException instead of returning null.

We propose a new form of the reference operator which returns null if the left side is null, and returns the result of the operation (on the right side) if not.

old code:
     if ( map == null ) {
return null;
} else {
return map.get(param);
}


new code:
     return map.?get(param);


The two code examples above will be similar, and, in fact, the class code will probably be exactly the same. It's a compiler-only effect.

0 Comments:

Post a Comment

<< Home