235. Do not use Optional just for getting a value

This problem gives the start of a suite of problems from the do not use category. The do not use category tries to prevent the overuse of Optional and gives several rules that can save us a lot of trouble. Nevertheless, rules have exceptions. Therefore, do not conclude that the presented rules should be avoided at all costs. As always, it depends on the problem.

In the case of Optional, a common scenario involves chaining its methods for the single purpose of getting some value.

Avoid this practice and rely on simple and straightforward code. In other words, avoid doing something like the following snippet of code:

public static final String BOOK_STATUS = "UNKNOWN";
...
// Avoid
public String findStatus() {
// fetch a status prone to be null
String status = ...;

return Optional.ofNullable(status).orElse(BOOK_STATUS);
}

And use a simple if-else block or the ternary operator (for simple cases):

// Prefer
public String findStatus() {
// fetch a status prone to be null
String status = null;

return status == null ? BOOK_STATUS : status;
}
..................Content has been hidden....................

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