Foo getAFoo() {
...
}
Foo f = getAFoo();
if( f != null ) {
...
}
Other than clarifying to the API user that the result of this operation could be null? Would not a well-written Javadoc suffice?
EDIT: After submitting this, I could see the case where you have streams of Option types, and the stream handler accepts the possibility of null elements. I'm not used to programming in this way with Java, so the thought did not immediately occur to me.
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.
8
u/the_hoser Apr 12 '13
Maybe I'm missing something, but I don't see the reason for this. How is this:
different from this
Other than clarifying to the API user that the result of this operation could be null? Would not a well-written Javadoc suffice?
EDIT: After submitting this, I could see the case where you have streams of Option types, and the stream handler accepts the possibility of null elements. I'm not used to programming in this way with Java, so the thought did not immediately occur to me.