Elvis operator

Reinier Zwitserloot reinier at zwitserloot.com
Thu Jul 16 17:24:45 PDT 2009


You couldn't use ?. for any method that returned a primitive type  
(unless we expect ?. to mean: returns the default (0/false/'\0')  
primitive if the LHS is null, which sounds like a bad idea to me), for  
starters. Also, often the act of calling the method is not optional,  
and if at that point the LHS is indeed null, then an NPE would be the  
correct action.

?. is great stuff when you need to do what it says on the tin: let the  
expression evaluate to null if the LHS is null (which implies that the  
LHS being null is a common and expected possibility). Using ?. instead  
of . as some sort of safety mechanism is bass ackwards. In other  
words, '.' should be the norm, and ?. should be used only after you  
realize that it the circumstance calls for its use.

For example, when the LHS being null is an unexpected possibility,  
using ?. just moves the problem forward time a little bit; things are  
very likely going to go wrong soon anyway. However, when they go  
wrong, they either go wrong without throwing an exception, making it  
harder to figure out there's a problem, and if you do get an  
exception, the methods mentioned in the stack trace are now even less  
related to the source of the problem.


As an aside, I saw this trick in the javac core code:

param.getClass(); //NPE

which is a much shorter way of writing:

if ( param == null ) throw new NullPointerException("param");

And I appear to be in the minority as I think the above (without any  
braces) is perfectly fine, readable, maintainable, properly styled code.

You do miss the ability to name the problem (NPEs thrown by the  
runtime don't have a message), and you should definitely comment it,  
as by itself it looks kind of funky. getClass() is just a randomly  
selected method that has no side effects and is fast.

  --Reinier Zwitserloot



On 2009/16/07, at 20:35, Alex Buckley wrote:

> Dierk,
>
> Thank you very much for writing.
>
> Putting ?: and ?. side-by-side shows they are dual in a type-theoretic
> sense. ?: returns a specific value of a specific type (indicating a
> default), while ?. returns a non-value of the bottom type. Since the
> bottom type is a subtype of all other types, the non-value will  
> swallow
> all messages sent to it. The non-value turns into the null reference  
> at
> assignment conversion or method invocation conversion, of course.
>
> Turning to more practical matters, do you have a sense of how often ?.
> is used in Groovy code? Why would anyone dereference with '.' when  
> they
> could use '?.' ? If '.' is still commonly used, is Groovy code  
> littered
> with as many == comparisons with null as Java code is?
>
> Alex
>




More information about the coin-dev mailing list