5 Modeling the possible absence of data

 

This chapter covers

  • Using Option to represent the possible absence of data
  • Understanding why null is a terrible idea
  • Whether you should use C# 8 nullable reference types

In chapter 4, I introduced you to the idea that types should precisely represent the data they encapsulate in order to write expressive function signatures. One particularly thorny issue is that of representing data that may not be available. For instance, when you register on a website, you typically have to provide your email address, but other details like your age and gender are optional. The website owner may want to process and analyze this data if it’s available.

“Wait a minute,” you’re probably thinking, “don’t we use null for this?” I’ll discuss null in section 5.5, but for the first part of this chapter, you could just pretend that null doesn’t exist and that we have to come up with a way to represent the possible absence of data.

When coding functionally, you never use nullever. Instead, FP uses the Option type to represent optionality. I hope to show you that Option provides a much more robust and expressive representation. If you’ve never heard of Option before, I ask you to suspend judgment, as the added value of Option may not be clear until you see it used in the next couple of chapters.

5.1 The bad APIs you use every day

5.2 An introduction to the Option type

5.3 Implementing Option

5.3.1 An idealized implementation of Option

5.3.2 Consuming an Option

5.3.3 Creating a None

5.3.4 Creating a Some

5.3.5 Optimizing the Option implementation

5.4 Option as the natural result type of partial functions

5.4.1 Parsing strings

5.4.2 Looking up data in a collection

5.4.3 The smart constructor pattern

5.5 Dealing with null