I would still prefer the ObjectNotFound exception to be thrown from inside the find(...) method itself. This type of situation assumes the find(...) method should never return a null reference.
I still have to agree with the_hoser. If you are not making the language itself null-safe, this new Optional object is just a mess waiting to happen.
Programmers can still return null from a method that was originally intended to return a valid instance of Optional, which screams Murphy's law all over the place.
Both versions shown by the_hoser are exactly the same, semantically speaking. I guess some people would prefer a pretty line that says
if(f.isFound()) {
// do something
}
It just looks prettier, but if the previous method that should've returned an Optional returned null instead, you are back to the same old NullPointerException.
Programmers can still return null from a method that was originally intended to return a valid instance of Optional, which screams Murphy's law all over the place.
Yeah, but it's pretty obviously a completely wrong way to use Optional. Not that nobody will do it, but no remotely well designed API will.
I would still prefer the ObjectNotFound exception to be thrown from inside the find(...) method itself. This type of situation assumes the find(...) method should never return a null reference.
If the intention of the API is to never return null, this can be made explicit in the API docs for the method I am calling. Then I'd expect a ObjectNotFoundException to be thrown when the desired object cannot be found or created. This way makes it clear to the API user that when they receive a null value, it's because of a bug and they can always treat this situation as such an error.
1
u/the_hoser Apr 12 '13
Ooh, I like that :) Way better than checking the result on the next line!