228. Returning an already-constructed default value

Let's assume that we have a method that returns a result based on Optional. If Optional is empty then the method returns a default value. If we consider the previous problem, then a possible solution can be written as follows:

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

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

Well, this is not a bad solution, but is not very elegant. A more concise and elegant solution will rely on the Optional.orElse() method. This method is useful for replacing the isPresent()-get() pair when we want to set or return a default value in case of an empty Optional class. The preceding snippet of code can be rewritten as follows:

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

return status.orElse(BOOK_STATUS);
}
But keep in mind that orElse() is evaluated even when the Optional class involved is not empty. In other words, orElse() is evaluated even if its value is not used. Having said that, it is advisable to rely on orElse() only when its argument is an already-constructed value. That way, we mitigate a potential performance penalty. The next problem addresses the case when orElse() is not the correct choice.
..................Content has been hidden....................

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