Monday, February 23, 2015

In Defence of Java 8’s Optional: Why and How to Use It


The problem with null is not that it was invented back in 1965, but that we are still struggling with it 50 years later. Any Java developer has probably seen and written code like this:








String result = service.find("id");
String value;
if (result != null) {
    value = result.trim();
} else {
    value = "<absent>";
}
System.out.println("Value: " + value);
In fact, most Java monoglots have probably experienced code like this so many times, they don’t even see the problem anymore. And yet, with Java 8, they have to deal with a solution: the Optional type.
I recently came across this article on Voxxed: Embracing the Void: 6 Refined Tricks for Dealing with Nulls in Java. It gives a nice rundown of strategies around the null reference. Sadly, it discourages the use of Java 8’s Optional. In this post I will explain why and how you should use Optional…

Lear More

No comments:

Post a Comment