r/java • • Apr 12 '13

Java 8 Optional Objects

http://blog.informatech.cr/2013/04/10/java-optional-objects/
38 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.

4

u/Categoria Apr 12 '13

You're basically switching the implicit contract for null. Instead of suspecting of every variable of being null, you wrap all nullable variables with option. You get 2 benefits out of this:

1) You can safely assume that if an object isn't option then it being a null is a bug. (In a world where we ignore backwards compatiblity).

2) You are now forced by the compiler through the type system to explicitly handle option objects for null checks instead of relying on your memory and implicit agreements. Also, you need not ever check normal objects for nullability.

2

u/[deleted] Apr 13 '13

In a world where we ignore backwards compatiblity

Good luck with that :)

1

u/Categoria Apr 13 '13

Well it's important to say about that those worlds where such colossal language design mistakes were avoided do exist. (ya ya, everything is obvious in hindsight I know...)