Chapter 11. Using Optional as a better alternative to null

 

This chapter covers

  • What’s wrong with null references and why you should avoid them
  • From null to Optional: rewriting your domain model in a null-safe way
  • Putting optionals to work: removing null checks from your code
  • Different ways to read the value possibly contained in an optional
  • Rethinking programming given potentially missing values

Raise your hand if you ever got a NullPointerException during your life as a Java developer. Keep it up if this Exception is the one you encounter most frequently. Unfortunately, we can’t see you at this moment, but we believe that there’s a high probability that your hand is raised now. We also guess that you may be thinking something like “Yes, I agree. NullPointerExceptions are a pain for any Java developer, novice, or expert. But there’s not much we can do about them, because this is the price we pay to use such a convenient, and maybe unavoidable, construct as null references.” This feeling is common in the (imperative) programming world; nevertheless, it may not be the whole truth and is more likely a bias with solid historical roots.

11.1. How do you model the absence of a value?

 

11.2. Introducing the Optional class

 
 
 
 

11.3. Patterns for adopting Optionals

 
 
 

11.4. Practical examples of using Optional

 
 
 
 

Summary

 
 
sitemap

Unable to load book!

The book could not be loaded.

(try again in a couple of minutes)

manning.com homepage
test yourself with a liveTest