Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best practice to avoid null-check conditional operator boilerplate

When it is not possible to use null object, what is the best practice to replace conditional operator null-checks boilerplate like this:

public String getEmployeeName() {
    return employee == null ? null : employee.getName();
}

Is there something like below in Java 8 or any utility library?

public String getEmployeeName() {
    return nullable(employee, employee -> employee.getName());
}

private <T, R> R nullable(T nullable, Function<T, R> doIfNotNull) {
    return nullable == null ? null : doIfNotNull.apply(nullable);
}
like image 383
Daniel Hári Avatar asked Feb 08 '23 09:02

Daniel Hári


2 Answers

I find return employee == null ? null : employee.getName(); to be the most readable, so perhaps it is the better solution instead of just making your code overly complex. It gets the job done, and there's nothing wrong with it - so might as well use it. That's what the conditional operator is for.

Often when trying to decide which programming pattern to use, it is best to use the pattern that is the most readable and the easiest for future maintainers of your code to understand.

like image 178
Parker Hoyes Avatar answered Feb 10 '23 21:02

Parker Hoyes


You could refactor your code to this:

public String getEmployeeName() {
    return Optional.ofNullable(employee).map(Employee::getName).orElse(null);
}

ofNullable creates an Optional value out of the given employee: if it is null, the empty Optional is returned; otherwise an Optional containing the employee is returned. Then, this Optional is mapped to the name of the employee using map, which returns a new Optional with the given mapper applied if the Optional is non empty and an empty Optional if the Optional is empty. Finally, orElse returns the name of the employee or null is the Optional is empty.

Having said that, I don't see any added value in having this code over the null-check and the conditional operator: it will likely have a better performance and may also be easier to read.

like image 25
Tunaki Avatar answered Feb 10 '23 23:02

Tunaki