Click here to Skip to main content
15,123,408 members
Articles / Programming Languages / Java
Posted 14 Oct 2015

Tagged as


9 bookmarked

Null is Optional

Rate me:
Please Sign up or sign in to vote.
4.33/5 (39 votes)
13 Dec 2015CPOL3 min read
Null is optional


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(); // NullPointerException at runtime

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:

// findUser("jonhdoe").address(); compile error!

Handling the absent value:

Optional<User> user = findUser("johndoe");
if(user.isPresent()) {

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();


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"));
if(foo.equals(foo2)) { // no NullPointerException, even if foo is absent
  // ...


In most cases, avoiding implicit nulls 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


This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


About the Author

Norway Norway
No Biography provided

Comments and Discussions

GeneralRe: A comment Pin
mrcellux15-Oct-15 10:14
Membermrcellux15-Oct-15 10:14 
GeneralRe: A comment Pin
moongha4215-Oct-15 11:30
Membermoongha4215-Oct-15 11:30 
GeneralRe: A comment Pin
mrcellux15-Oct-15 13:00
Membermrcellux15-Oct-15 13:00 
QuestionWell, yah... Pin
Michael Breeden15-Oct-15 8:21
MemberMichael Breeden15-Oct-15 8:21 
AnswerRe: Well, yah... Pin
mrcellux15-Oct-15 10:32
Membermrcellux15-Oct-15 10:32 
QuestionClear and to the point! Pin
SteveHolle15-Oct-15 6:15
MemberSteveHolle15-Oct-15 6:15 
AnswerRe: Clear and to the point! Pin
KP Lee12-Nov-15 0:54
MemberKP Lee12-Nov-15 0:54 
QuestionLike it Pin
Louis van Alphen14-Oct-15 9:22
MemberLouis van Alphen14-Oct-15 9:22 
I like this, even though it adds no real functionality, it establishes the convention. Same situations that I have grappled with ...

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.