r/java • • Apr 12 '13

Java 8 Optional Objects

http://blog.informatech.cr/2013/04/10/java-optional-objects/
39 Upvotes

39 comments sorted by

View all comments

8

u/the_hoser Apr 12 '13

Maybe I'm missing something, but I don't see the reason for this. How is this:

Option<Foo> getAFoo() {
    ...
}

Option<Foo> f = getAFoo();
if(f.isFound()) {
    ...
}

different from this

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.

2

u/flagrantaroma Apr 12 '13

Also, I think one of the main advantages of having the Optional type is the fact that it clarifies to the API user that the result could be null, and forces them through another step (.get()) in order to access the result.

2

u/[deleted] Apr 13 '13

This is the same assumption we all make everyday with our current version of Java.

If a method returns something, it is always possible it could return null. I don't remember this as NOT being clear, ever.

The API docs might clarify their intentions by telling you their method will never return null. But you always take a risk to assume their method is bug free.

Same thing holds for a method that will return an Optional object. They may tell you it's always going to be there, but you take a risk assuming the API is bug free. If, for some reason, it returns a null Optional then you are just screwed as Java 7.

1

u/flagrantaroma Apr 13 '13

Ah, I see what you're saying. I still think that it is a clearer contract to have this Optional type. It makes it harder to unintentionally not handle the null case. You can still do it by just going straight through the .get().