Click here to Skip to main content
15,878,959 members
Articles / Programming Languages / Java
Article

Null is Optional

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

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:

Java
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:

Java
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."

Java
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:

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

Handling the absent value:

Java
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:

Java
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:

Java
interface User {
  String name();
  Address address();
  BankAccount account();
}

to:

Java
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:

Java
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:

Java
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)) { // no NullPointerException, even if foo is absent
  // ...
}

Conclusion

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

License

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


Written By
Norway Norway
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
SuggestionThat is not the solution Pin
Alexandru Lungu9-Nov-15 3:51
professionalAlexandru Lungu9-Nov-15 3:51 
GeneralRe: That is not the solution Pin
mrcellux9-Nov-15 21:35
mrcellux9-Nov-15 21:35 
GeneralRe: That is not the solution Pin
Alexandru Lungu10-Nov-15 0:59
professionalAlexandru Lungu10-Nov-15 0:59 
GeneralRe: That is not the solution Pin
mrcellux10-Nov-15 10:56
mrcellux10-Nov-15 10:56 
GeneralRe: That is not the solution Pin
Alexandru Lungu11-Nov-15 4:33
professionalAlexandru Lungu11-Nov-15 4:33 
GeneralRe: That is not the solution Pin
mrcellux11-Nov-15 4:48
mrcellux11-Nov-15 4:48 
GeneralA comment Pin
moongha4215-Oct-15 8:06
moongha4215-Oct-15 8:06 
GeneralRe: A comment Pin
mrcellux15-Oct-15 9:14
mrcellux15-Oct-15 9:14 
I added that code example on purpose to emphasize a similarity between the two. A beginner grasps the concept a lot easier this way.

Towards the end of the article you can find other examples that offer simpler syntax. Eg if you don't need an else you can do:
Java
user.ifPresent(user -> { user.foo(); })

Also note that none of those higher level constructs makes you call that get(). It's only for low level use, and it actually helps by forcing you to think about the value being optional.

In any case, the main point is not the syntax, but the concept of avoiding the use of null references.
GeneralRe: A comment Pin
moongha4215-Oct-15 10:30
moongha4215-Oct-15 10:30 
GeneralRe: A comment Pin
mrcellux15-Oct-15 12:00
mrcellux15-Oct-15 12:00 
QuestionWell, yah... Pin
Michael Breeden15-Oct-15 7:21
Michael Breeden15-Oct-15 7:21 
AnswerRe: Well, yah... Pin
mrcellux15-Oct-15 9:32
mrcellux15-Oct-15 9:32 
QuestionClear and to the point! Pin
SteveHolle15-Oct-15 5:15
SteveHolle15-Oct-15 5:15 
AnswerRe: Clear and to the point! Pin
KP Lee11-Nov-15 23:54
KP Lee11-Nov-15 23:54 
QuestionLike it Pin
Louis van Alphen14-Oct-15 8:22
Louis van Alphen14-Oct-15 8:22 

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.