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);
}
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With