We help IT Professionals succeed at work.

Avoiding null checks in java

Rohit Bajaj
Rohit Bajaj asked
I have the following code :
if (task.getCompletor() != null) {

The getCompletor returns a User -  :
public WorkflowUser getCompletor() {
        return completor;

what are the ways i could avoid the null check.
One way i can think of to user a NullWorkflowUser class so instead of directly returning the completor from the getter i return this object in case its null this way i dont have to have a null check and i could write the definitions which will be null for the methods inside it.
I have read about Optionals but never used it.
Can that be used here.
Which is a better approach the NullWorkflowUser or the Optional one.

And any other alternatives in java.
Watch Question

Distinguished Expert 2019
1) If you want to use a NullWorkflowUser you will still need to check for null values, otherwise how do you know how to instantiate a NullWorkflowUser object instead of the WorkflowUser?

2) You can use Optional but you will need to wrap everything in an Optional class, e.g. Optional<WorkflowUser>. But this is a clearer solution since with optional you have several advantages over a null value:
a) you explicitly express that the value is optional
b) you clarify that optional is a perfectly valid value and that an optional value is not an application error (for example if you get a null value you cannot know if this is an application error, e.g. you forgot to initialise the value, or a business requirement, the object can indeed be null)

Of course there are disadvantages to using Optional, namely that they are not serialisable (if you need serialisation, although there are workarounds) and that you have to wrap up everything to an Optional.

3) There is another way, to use assert, but assert will throw an error if the condition is false, so I do not think this is what you're looking for.

If I had to choose from all the points above, and you absolutely need to remove all null checks, I would go with the Optional.