Optional – dealing with uncertainty

Since it was created, null has been used and misused by developers innumerable times in innumerable programs. One of the common cases for null is, among others, to represent the absence of a value. That is not convenient at all; it could either represent the absence of a value or the abnormal execution of a piece of code.

Moreover, in order to access variables that can potentially be null, and mitigate undesired runtime exceptions like NullPointerException, developers tend to wrap variables with an if statement so those variables are accessed in safe mode. Although it works, this protection against nulls adds some boilerplate that has nothing to do with the functionality or the goal of the code:

if (name != null) {
// do something with name
}

The preceding code overcomes the problems that the creator of null spotted in his famous quote during a conference in 2009:

"I call it my billion-dollar mistake. It was the invention of the null reference in 1965. At that time, I was designing the first comprehensive type system for references in an object oriented language (ALGOL W). My goal was to ensure that all use of references should be absolutely safe, with checking performed automatically by the compiler. But I couldn't resist the temptation to put in a null reference, simply because it was so easy to implement. This has led to innumerable errors, vulnerabilities, and system crashes, which have probably caused a billion dollars of pain and damage in the last forty years."

– Tony Hoare

With the release of Java 8, the utility class called Optional was included as an alternative to the preceding code block. Among other benefits, it brings compilation checks and zero boilerplate code. Let's see Optional in action with a simple example.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.133.159.223