Click here to Skip to main content
15,900,461 members
Articles / All Topics
Tip/Trick

Null is Optional

Rate me:
Please Sign up or sign in to vote.
4.33/5 (39 votes)
11 Nov 2015CPOL3 min read 66.5K   9   47
Null is optional
This is a new version of the currently published article.

Introduction

Null reference is commonly used to express the absence of value, it has certain drawbacks though in many languages. Let's take a look at the following method:

User findUser(String name)

What happens when that user can't be found? Throwing an exception is not a good option in many contexts (eg flow control). An alternative is returning a null reference, which seemingly fits the purpose well. It has an issue though: the possibility of a null value is implicit, the interface doesn't reveal it. Why is that a big deal? Not null or null requires different handling: eg if user is null do this, otherwise do that. When someone uses that method, things can go wrong in several ways:

  • Null check is not performed (hasn't been considered or forgotten) and a NullPointerException will be thrown in some cases
  • Time is invested in making sure that implementation never returns a null reference.. Then hope for the best that won't change in the future.
  • Null check is done speculatively, even if it's not needed

The cause for these issues is the communication of intent on the interface is lacking. Revealing nullability on the interface avoids these issues.

Some languages don't allow null references by default and have special syntax for marking nullable references. Most languages can't do this - in most cases for compatibility reasons - and support an alternative to address the issue: the option type. Let's take a look at java's Optional for instance.

C#
Optional<User> findUser(String name);

Now the interface communicates clearly that a user may not be present in the result and the client is forced to take that into account:

C#
Optional<User> user = findUser("johndoe");
// user.foo(); compile error
if(user.isPresent()) {
   user.get().foo();
}

With consistent use of Optional, it is possible to establish a powerful convention of avoiding the use of null references. Putting this to the context of a system, it transforms an interface from:

C#
A a();
B b();
C c();
D d();

To:

C#
A a();
B b();
Optional<C> c();
D d();

The client knows c may not return a value, while the others always do (the convention at play here). The compiler will even force the client to handle the optional value c returns. If d becomes optional at some point in the future, all the client code will be forced to conform.

As a small bonus, there is some additional syntax sugar that simplifies code in a lot of scenarios:

C#
Optional<String> foo = Optional.ofNullable(someThirdPartyCodeThatMayReturnNull());
println(foo.orElse("Hey, no value here"));
println(foo.orElseThrow(() -> new RuntimeException("I really expect a value here")));
someThirdPartyCodeRequiringNull(foo.orElse(null));

Conclusion

In most cases avoiding implicit nulls as much as possible can do wonders to a codebase, making it a much safer place to be. Disadvantages? In most cases there aren't, but as to everything there are exceptions. The Optional is a heap object, this needs to be considered in extreme cases. Also 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 some nullable references.

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

Discussions on this specific version of this article. Add your comments on how to improve this article here. These comments will not be visible on the final published version of this article.
 
QuestionI know this is an old post Pin
Sacha Barber2-Feb-18 1:49
Sacha Barber2-Feb-18 1:49 
GeneralMy vote of 5 Pin
dmjm-h8-Dec-15 9:50
dmjm-h8-Dec-15 9:50 
QuestionWhats so bad about null checking? Pin
GerVenson8-Dec-15 2:11
professionalGerVenson8-Dec-15 2:11 
AnswerRe: Whats so bad about null checking? Pin
mrcellux8-Dec-15 4:09
mrcellux8-Dec-15 4:09 
Question[My vote of 1] Dummy article Pin
Thornik28-Nov-15 12:47
Thornik28-Nov-15 12:47 
AnswerRe: [My vote of 1] Dummy article PinPopular
mrcellux28-Nov-15 21:30
mrcellux28-Nov-15 21:30 
GeneralRe: [My vote of 1] Dummy article Pin
Eddy Vluggen31-Jan-18 14:35
professionalEddy Vluggen31-Jan-18 14:35 
PraiseWhy I like this Pin
MuThink27-Nov-15 1:49
MuThink27-Nov-15 1:49 
GeneralRe: Why I like this Pin
Eddy Vluggen31-Jan-18 14:37
professionalEddy Vluggen31-Jan-18 14:37 
QuestionIsn't this EXACTLY what TryParse is for? Pin
Enigmaticatious23-Nov-15 15:11
Enigmaticatious23-Nov-15 15:11 
AnswerRe: Isn't this EXACTLY what TryParse is for? Pin
mrcellux23-Nov-15 21:53
mrcellux23-Nov-15 21:53 
GeneralRe: Isn't this EXACTLY what TryParse is for? Pin
Enigmaticatious24-Nov-15 13:48
Enigmaticatious24-Nov-15 13:48 
GeneralRe: Isn't this EXACTLY what TryParse is for? Pin
mrcellux24-Nov-15 18:27
mrcellux24-Nov-15 18:27 
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 

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.