Chapter 15. Null

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

15.0 Introduction

Most programmers use null heavily. It is comfortable, efficient, and fast. And yet software developers have suffered a bazillion problems related to its use. This chapter highlights the problems with null usage and how to solve them.

Null is a flag. It represents different situations depending on the context in which it is used and invoked. This yields the most serious error in software development: coupling a hidden decision in the contract between an object and who uses it. It also breaks the bijection principle by representing multiple elements of the domain with the same entity and forcing you to make contextual interpretations. All objects should be as specific as possible and have a single responsibility (see Recipe 4.7, “Reifying String Validations”), but the least cohesive object of any system is the wildcard: null, which is mapped to several different concepts in the real world.

15.1 Creating Null Objects

Problem

You use null.

Solution

Null is schizophrenic and doesn’t exist in the real world. Null’s creator and Turing Award–winner Tony Hoare regretted it, and programmers around the world suffered for it. You can replace null using null objects.

Discussion ...

Get Clean Code Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.