Avatar of Rohit Bajaj
Rohit Bajaj
Flag for India asked on

Avoiding null checks in java

Hi,
I have the following code :
if (task.getCompletor() != null) {
                task1.setCompletorGuid(task.getCompletor().getUserGuid());
            }

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

Avatar of undefined
Last Comment
girionis

8/22/2022 - Mon
ASKER CERTIFIED SOLUTION
girionis

THIS SOLUTION ONLY AVAILABLE TO MEMBERS.
View this solution by signing up for a free trial.
Members can start a 7-Day free trial and enjoy unlimited access to the platform.
See Pricing Options
Start Free Trial
GET A PERSONALIZED SOLUTION
Ask your own question & get feedback from real experts
Find out why thousands trust the EE community with their toughest problems.
Experts Exchange has (a) saved my job multiple times, (b) saved me hours, days, and even weeks of work, and often (c) makes me look like a superhero! This place is MAGIC!
Walt Forbes