September 2019
Intermediate to advanced
816 pages
18h 47m
English
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:
// Avoidpublic 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:
// Avoidpublic String findStatus() { Optional<String> status = ...; // ...