Click here to Skip to main content
15,890,123 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 66K   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

 
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 
mrcellux wrote:
it returns a bool, not the result you're interested in


You DO realize that ALL control is determined by booleans. Whether directly as a boolean result or by performing an expression that returns a boolean (ie does X == null). So for you to say that it is a reason why it is not elegant is because it cuts directly to the chase and returns the EXACT value you require to control whether a value is absent or not simply shows you fail to understand simple programming.

You have made an arbitrary (and poor) presumption that you MUST return the result you are interested in, which means you are convoluting your original design by stating that it must not only provide a means of controlling whether a value is present, but also return that value, thus you have created the problem you just happen to have a solution for.

That is very poor coding

mrcellux wrote:
t forces you to handle the absent value immediately - or wrap and propagate your result together with that bool to allow you to do so later


You cannot have it both ways. You cannot completely contradict yourself in the same sentence by saying it is both bad that you are forced to deal with it immediately, and that you have to wrap it to deal with it later. Why would you even retrieve the value if you did not want to either deal with it immediately OR deal with it later?

Again you are making a very flawed design decision that absent values must support both immediate handling and later handling equally.

Again that is poor coding

mrcellux wrote:
ou need to create and pass in a mutable object to access your result (this is the biggest issue)


Can you explain this better, it isn't clear what you mean and I have a feeling you are creating a problem in order to say that it is a problem. You are creating an instance of a class to capture the result (and that is good?) but if you actually store the result in a variable then that is bad?

That makes no sense


mrcellux wrote:
it requires you to prefix your methods with try to express your intent


Are you serious??? You are claiming that it is bad to have the names of your methods actually provide you with information about the task it is performing? Weren't you the one going on about how interfaces need to explain what is expected? But now you are complaining that the text "try" is required to express intent???

Seriously... STOP programming. You clearly have no clue about the purpose of method names. You DO understand the need for verbs don't you?

I am sorry, but I stand by my original comment that this solution you have suggested is needlessly bloated, extremely inelegant, it creates problems that it then magically says it can solve, and the "reasons why" a simple solution are not good are all manufactured or just plain convoluted.

If you seriously think someone when coming up with a design says "Mmmm... I need to add 'try' to the front of this method, I know, i will write an entire new class and add an overhead, that is a much better solution that making my method name actually tell me what it is doing"

You have to be joking!
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.