Click here to Skip to main content
15,867,308 members
Articles / Programming Languages / Java

Null is Optional

Rate me:
Please Sign up or sign in to vote.
4.33/5 (39 votes)
13 Dec 2015CPOL3 min read 65.4K   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

 
GeneralRe: Isn't this EXACTLY what TryParse is for? Pin
Enigmaticatious25-Nov-15 17:16
Enigmaticatious25-Nov-15 17:16 
GeneralRe: Isn't this EXACTLY what TryParse is for? Pin
mrcellux25-Nov-15 20:20
mrcellux25-Nov-15 20:20 
GeneralRe: Isn't this EXACTLY what TryParse is for? Pin
Enigmaticatious26-Nov-15 10:40
Enigmaticatious26-Nov-15 10:40 
GeneralRe: Isn't this EXACTLY what TryParse is for? Pin
Jay Marte25-Nov-15 21:50
Jay Marte25-Nov-15 21:50 
GeneralRe: Isn't this EXACTLY what TryParse is for? Pin
Enigmaticatious26-Nov-15 10:51
Enigmaticatious26-Nov-15 10:51 
GeneralRe: Isn't this EXACTLY what TryParse is for? Pin
mrcellux26-Nov-15 12:00
mrcellux26-Nov-15 12:00 
GeneralRe: Isn't this EXACTLY what TryParse is for? Pin
Enigmaticatious26-Nov-15 13:49
Enigmaticatious26-Nov-15 13:49 
GeneralRe: Isn't this EXACTLY what TryParse is for? Pin
mrcellux26-Nov-15 18:16
mrcellux26-Nov-15 18:16 
GeneralRe: Isn't this EXACTLY what TryParse is for? Pin
Enigmaticatious29-Nov-15 10:57
Enigmaticatious29-Nov-15 10:57 
GeneralRe: Isn't this EXACTLY what TryParse is for? Pin
mrcellux26-Nov-15 12:16
mrcellux26-Nov-15 12:16 
GeneralRe: Isn't this EXACTLY what TryParse is for? Pin
Jay Marte26-Nov-15 22:02
Jay Marte26-Nov-15 22:02 
GeneralRe: Isn't this EXACTLY what TryParse is for? Pin
Enigmaticatious29-Nov-15 11:03
Enigmaticatious29-Nov-15 11:03 
QuestionSometimes returning a null value could have a benefit Pin
KP Lee12-Nov-15 0:30
KP Lee12-Nov-15 0:30 
AnswerRe: Sometimes returning a null value could have a benefit Pin
mrcellux12-Nov-15 1:24
mrcellux12-Nov-15 1:24 
QuestionType changed Pin
Nelek11-Nov-15 12:25
protectorNelek11-Nov-15 12:25 
QuestionUnneccessary wrapper Pin
Dr. Plecostomus11-Nov-15 7:40
Dr. Plecostomus11-Nov-15 7:40 
AnswerRe: Unneccessary wrapper Pin
mrcellux11-Nov-15 10:47
mrcellux11-Nov-15 10:47 
PraiseNice and clear explanation Pin
Jay Marte9-Nov-15 23:25
Jay Marte9-Nov-15 23:25 
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 

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.