Tuesday, May 13, 2014

Optional Type in Java 8

There are many new features like lambdas introduced in Java 8, but I thought of going through smaller ones. The current topic is one of such smaller changes but on the contrary quite interesting J

We all know that code is never expected to fail with a NullPointerException and proper handling of it is required. Doing NULL check is a very basic thing and expected out of every programmer. 

A new type Optional was introduced to indicate that the return value may be NULL and sort of enforces programmers to do a NULL check. I won't be discussing this feature in every minute detail for the reason there are many pretty good sources out there explaining the same. Blog Tired of Null Pointer Exceptions explains this very well.

The point that I want to emphasize here is about the programs which return NULL. One of the primary reason for introduction of Optional is because most of the programmers forget to do a NULL check but at the same time the code which returns NULL is forgiven. In my view returning NULL value is a bigger crime than not doing a NULL check and the reason being NULL shouldn't be used as an alternative for expressing nothing. Use an empty value instead of NULL; for example return an empty list instead of NULL. 

Also if you carefully go through the JAVA documentation for Optional.get() it says 'If a value is present in this Optional, returns the value, otherwise throws NoSuchElementException.' What this means? Now there are very good chances that programmers start facing more NoSuchElementException instead of NullPointerException.

In order to express the seriousness of the mistake in which the code returns a NULL value is presented very well in the blog post Empty !!!..

No comments:

Post a Comment