Chapter 9. Handling null with Optionals
As a Java developer, you’ve likely encountered your share of NullPointerExceptions, and then some.
Many people call the null reference a billion-dollar mistake.
Actually, the inventor of null itself originally coined that phrase:
I call it my billion-dollar mistake.
It was the invention of the
nullreference 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 anullreference 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.
Sir Charles Antony Richard Hoare, (QCon London 2009)
Although there is no absolute consensus on how to deal with this “mistake,” many programming languages have a proper and idiomatic way of handling null references, often directly integrated into the language itself.
This chapter will show you how Java handles null references and how to improve it in your code with the Optional<T> type and its functional API, and learn how, when, and when not to use Optionals.
The Problem with null References
Java’s handling of the absence of a value depends on the type. All primitive types have default values, e.g., a zero ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access