227. Optional.get() and missing value

So, if we have decided to call Optional.get() to fetch the value wrapped in Optional, then we shouldn't do it as follows:

Optional<Book> book = ...; // this is prone to be empty

// Avoid
// if "book" is empty then the following code will
// throw a java.util.NoSuchElementException
Book theBook = book.get();

In other words, before fetching the value via Optional.get(), we need to prove that the value is present. A solution consists of calling isPresent() before calling get(). This way, we add a check that allows us to handle the missing value case:

Optional<Book> book = ...; // this is prone to be empty

// Prefer
if (book.isPresent()) {
Book theBook = book.get();
... // do something with "theBook"
} else {
... // do something that does not call book.get()
}
Nevertheless, keep in mind that the isPresent()-get() team has a bad reputation, and so use it with caution. Consider checking the next problems, which provide alternatives to this team. Moreover, at some point, Optional.get() is likely to be deprecated.
..................Content has been hidden....................

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