Daniel Hári Daniel Hári - 1 year ago 91
Java Question

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);

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download