Introduction
Null
reference is commonly used to express the absence of value. It has a certain drawback though in most languages (more specifically in statically typed ones allowing nullable references without explicit syntax). Let's take a look at the following method:
User findUser(String name);
What happens when that user can't be found? Returning null
expresses the concept of an absent value in probably the simplest way, but it has a specific drawback: the possibility of the null
reference is implicit, the interface doesn't reveal this. Why is that a big deal? Null references need handling, otherwise NullPointerException
may occur at runtime, a very common error:
findUser("jonhdoe").address();
Generally not all the values are nullable in a system. Indicating where exactly handling is needed is useful to reduce both risks and unnecessary effort. Documentation or meta code can communicate nullability, but they're not ideal: they are possible to miss and lack compile safety.
Some languages don't allow nullable
references by default and have special syntax for allowing them. Most languages can't do this - in most cases for compatibility reasons - and have an alternative to address the issue by making use of their type type system: the option type. It's useful to know about this pattern as it can be easily implemented in most languages - if it's not implemented already. Let's take a look at Java 8's Optional for instance. "A container object which may or may not contain a non-null value."
Optional<User> findUser(String name);
This interface communicates clearly that a user may not be present in the result and the client is forced to take that into account:
Handling the absent value:
Optional<User> user = findUser("johndoe");
if(user.isPresent()) {
user.get().address();
}
This example is intentionally kept somewhat similar to how null references are often handled. A more idiomatic way of doing the same:
findUser("johndoe").ifPresent(user -> user.address());
It's interesting to consider the effects of the pattern in the wider context of a system. With consistent use of Optional
, it is possible to establish a powerful convention of avoiding the use of null
references. It transforms an interface from:
interface User {
String name();
Address address();
BankAccount account();
}
to:
interface User {
String name();
Address address();
Optional<BankAccount> account();
}
The client can see a user may not have a bank account
and can assume it always has a name
and address
(the convention at play here). The domain model became more expressive. Such practice works well with changes: eg if address
becomes optional at some point in the future all client code will be forced to conform. The code examples so far presented the effects on method signatures, the same benefits apply to class fields or local variables:
class Address {
String city;
Optional<String> street;
}
As a small bonus, there is some more syntax sugar that simplifies code in a lot of scenarios:
Optional<String> foo = Optional.ofNullable(thirdPartyApiThatMayReturnNull());
String foo2 = foo.orElse("No value.. take this default one.");
String foo3 = foo.orElseThrow(() -> new RuntimeException("I really can't work without a value though"));
thirdPartyApiExpectingNull(foo.orElse(null));
if(foo.equals(foo2)) {
}
Conclusion
In most cases, avoiding implicit null
s as much as possible can do wonders to a codebase, makes it a much safer place to be. Disadvantages? Patterns like the option type work well in most cases, but as with everything there are exceptions: it's a heap object, this needs to be considered if the number of objects is extremely high. There may be specific scenarios where such practice doesn't deliver real value or is impractical. 3rd party code may also force the use of null
references.
An example of the use of optional: the java 8's Stream API