Best practice to avoid zero-conditional conditional statement pattern

When it is not possible to use a null object, it is best to replace the null-checks conditional statement with a pattern like this:

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

Is there something like below in Java 8 or in any 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);
}
+4
source share
3 answers

I find it to return employee == null ? null : employee.getName();be the most readable, so maybe this is the best solution, and not just making your code overly complex. He does his job, and there is nothing wrong with that - so you can use it. This condition is a conditional statement.

, , , , .

+5

:

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

ofNullable Optional : null, Optional ; Optional, . Optional , map, Optional mapper Optional Optional, Optional . , orElse null Optional .

, null -check : , , , .

+4

Java 8 has a new class Optionallike

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

employeenever will be null, but can be "empty".

Then the method getEmployeeName()can 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);
}
-1
source

Source: https://habr.com/ru/post/1618667/


All Articles