Devil in a tiny detail

Often we try to avoid unexpected evil NullPointerExceptions, especially once we work with POJOs. However sometimes instead of fixing the problem, one unintentionally introduces it.

What could be less harmful than checking for NULL and only if the object is good, getting its property? Best, if you could do it inline!

MyType object = new MyType();
Long someValue = object != null ? object.getValue() : 0L;

However, there is small Java devil is hiding in here. Did you notice?

Try to run this code then:

MyType object = new MyType();
Long value = null;
Long someValue = object != null ? value : 0L;

Ooops… java.lang.NullPointerException!

The reason for that is the concept of autoboxing. In this case the value is automatically unboxed into a primitive type long, so by trying to unbox NULL, it throws NPE.

“Autoboxing and unboxing blur the distinction between primitive types and reference types, but they do not eliminate it”.

So how to make this code work? One way: simply avoid primitives in such cases! Try this snippet now:

MyType object = new MyType();
Long someValue = object != null ? object.getValue() : new Long(0);
// but be aware your someValue might be null in the end!
assertThat(someValue, is(nullValue()));

Lesson introduced by my colleague learned: use inline expressions carefully 😉

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s