229. Returning a non-existent default value

Let's assume that we have a method that returns a result based on an Optional class. If this Optional class is empty then the method returns a computed value. The computeStatus() method computes this value:

private String computeStatus() {
// some code used to compute status
}

Now, a clumsy solution will rely on the isPresent()-get() pair, as follows:

// Avoid
public String findStatus() {
Optional<String> status = ...; // this is prone to be empty

if (status.isPresent()) {
return status.get();
} else {
return computeStatus();
}
}

Even if this solution is clumsy, it is still better than relying on the orElse() method, as follows:

// Avoid
public String findStatus() {
Optional<String> status = ...; // this is prone to be empty

// computeStatus() is called even if "status" is not empty
return status.orElse(computeStatus());
}

In this case, the preferred solution relies on the Optional.orElseGet() method. The argument of this method is  Supplier;, and so it is executed only when the Optional value is not present. This is much better than orElse() since it saves us from executing extra code that shouldn't be executed when the Optional value is present. So, the preferred solution is as follows:

// Prefer
public String findStatus() {
Optional<String> status = ...; // this is prone to be empty

// computeStatus() is called only if "status" is empty
return status.orElseGet(this::computeStatus);
}
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.144.30.236