Is it true that since Java 1.8 returning Optional
object is more preferable than throwing an exception?
Increasingly i see the code like this:
p
It is possible to abuse exceptions, nulls, and optionals equally. In this particular case, I think you're probably abusing optional, because you're silently hiding a precondition violation and converting it into a normal return. On receipt of an empty optional from your code, the caller has no way of differentiating "the thing I was looking for wasn't there" and "I asked an invalid question."
Because Optional is new, there is also a tendency for it to be over-used; hopefully over time the right patterns will be internalized.
Optional is an example of the null object pattern; it provides a safe way to say "nothing was there" when "nothing there" is a reasonable expected outcome. (Returning an empty array or an empty collection are similar examples in those domains.) Whether you want to represent "nothing there" by null/optional vs an exception is generally a function of whether "nothing there" is a commonly expected situation, or whether it is exceptional. For example, no one wants Map.get
to throw an exception if the mapping is not present; mapping-not-present is an expected, not exceptional, outcome. (If we had Optional
in 1997, Map.get
might have returned an Optional
.)
I don't know where you heard the advice that Optional is preferable to exceptions, but whoever told you that was ill-informed. If you threw an exception before, you probably should still throw an exception; if you returned null before, you can consider returning Optional
instead.