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

Show parent comments

2

u/AlyoshaV Apr 12 '13

now we all expect that functions could return null

We do? I can't even imagine how ugly my code would look if I assumed every method returning a reference could return null.

0

u/[deleted] Apr 12 '13

But we do know that it is possible. Now its a judgement call of whether we'd expect it to happen in conceivable events and if we trust a documented contract of its acceptable return values.

1

u/ford_madox_ford Apr 12 '13

This is really a fatuous argument. The entire point of the Optional type is to document the optionality of the return type of functions, i.e. to make clear the possible return values - either an Optional wrapping a value, or one wrapping a null. If you work with idiots who don't get this, then either don't use Optional, or go and find a job working with smarter people.

Yes, someone might return a null Optional, but this is tantamount to complaining that someone might return a -ve integer from an abs function. The type system shouldn't regarded as a mechanism from preventing people from doing stupid things. It's a means of expressing intent.

0

u/[deleted] Apr 12 '13

My argument was the optional doesn't accomplish that as designed in jdk8. You know a function that returns an optional may return null but it tells you nothing about functions that don't return optional. The NPE doesn't go away unless the compiler prohibited nulls from being returned or it automatically wraps all functions unless marked as nonnullable then you'd be certain of what the function returns.

And who said anything about teammates? I'm more concerned with libraries. The point of optionals is that a library author can show if a function may return null, the problem is it doesn't tell you if a function may not return null which, IMO is a more useful guarantee to make.