简体   繁体   中英

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

I find return employee == null ? null : employee.getName(); 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.

Java 8 has the new Optional class, eg

private Optional<Employee> employee = Optional.empty();

public Optional<Employee> getEmployee() {
    return this.employee;
}
public void setEmployee(Employee employee) {
    this.employee = Optional.of(employee); // null not allowed
}
public void removeEmployee() {
    this.employee = Optional.empty();
}

The employee will never be null , but may be "empty".

The getEmployeeName() method can then be implemented in two ways:

// Returning Optional (never null)
public Optional<String> getEmployeeName() {
    return this.employee.map(Employee::getName);
}

// Standard getter (may return null)
public String getEmployeeName() {
    return this.employee.map(Employee::getName).orElse(null);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM