| Why is Optional<> better then throwing an exception or returning a null? The way I see it it's like this: Optional<Integer> num = getSomeRiskyNumber();
if (!num.isPresent())
return ... code to bubble up a blank optional
vs Integer num = getSomeRiskyNumber();
if (num == null)
... throw exception or return null
I get that the author has adopted a more functional programming methodology for dealing with their data but for some tasks this isn't acceptable. To just return 1 value you've allocated at least one object (Optional) and make at least 2 function calls on it (isPresent() and get()).You get `if (value == null)` for free. Throwing exceptions is very heavy and I'd place Optional<> above that but there isn't any way to signify the error that you acctually got. You'd need to make an Optional<Maybe<T>> where Maybe<T> supports error/exceptions. Maybe Maybe<T> holds data and you can extend it with BadMaybe<T> who extends exception or something so you can put that in instead of your value to signal your exception. I don't see the benifit. Maybe I'm just crazy but `if (v == null)` has all the features Optional has for less of an overhead and less cognitive load. (If you're afraid of NPEs then just document all the return states of your methods and use @nullable to show when you need to check. IIRC IntellJ catches that kind of mistake). |
Null ruins that. It's a known source of runtime exceptions, and it is not a compilation error to return null or forget the null-check. It is a compilation error to pretend that an Optional<T> is just a T. The Java compiler is not smart enough to prevent you from doing something silly like calling get() on Optional<T> without checking isPresent() first, but at least it gives you something.
Also Optional has some really nice creature comforts. It gives you the ability to map to compose an Optional<T> with functions that couldn't care less about the Optionality, and it lets you use flatMap to chain successive calls that might fail together, avoiding an arbitrary number of null checks (that you might forget!) in your code.
Frankly arguing against Optional<T> is like arguing against map on lists/streams and saying that for is good enough for you. You can do it, but I think you'd be nuts to work against yourself like that.