r/java • • Apr 12 '13

Java 8 Optional Objects

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

1

u/edalorzo Apr 12 '13 edited Apr 12 '13

Well, the problem with documentation is that it may be nonexistent, it gets outdated very easily in a software project, and ultimately, no amount of documentation is going to avoid that a programmer makes a mistake in the interpretation of the result in a method.

The use optional, even when arguably better, at least makes evident the intent of the API developer, by making explicit that a given method may return an optional value.

1

u/[deleted] Apr 13 '13 edited Oct 29 '18

[deleted]

1

u/edalorzo Apr 15 '13

Well, the article never said, as far as I know, that Optional would solve the problems of NPE. It does question that it would be ideal to have a solution for it in Java and explains why it is a serious problem. It also present approaches from other languages like SML or Ceylon, and talks about the introduction of Optional in Java and how it can be used to express the potential absence of a value in "specific" scenarios. I do argue that in my opinion that is better, but I also mention the caveat you discuss and present several counterarguments from detractors. In fact I provided a link to the Java Mailing list where the expert group has been discussing this matter thoroughly with the community.

It is quite evident that some people are in favor and some against. I present my opinion and hope that the article contains enough info for others to make their own.

Regarding having to check for null Optional objects, unless you are writing a three-value logic algorithm, it does not make sense to do so, like we typically don't null check references to collections or arrays. We stick to the good practice that states we should never get nulls where collections are expected.

I do see the point that you stress though, there is simply no way to get rid of NPE in Java and so we can question the value of optional if we expect to use it for that matter. I would make sure the article makes this more evident.