Use of the Optional<T> return type in Sponge

Why are you using Optional<T> as a return value? What’s so bad about returning null?
It just makes the code complicated, I don’t really see the advantage.

The Guava Team says that ‘the advantage is its idiot-proof-ness’, but idiots will just use optional.get().getName() and it throws an exception, just like (null).getName(); throws an exception.

I think just returning the object or null is more intuitive!

Example Code:

Optional<Integer> possible = Optional.of(5); possible.isPresent(); // returns true possible.get(); // returns 5

Occurence in Sponge API:

Discussion:

1 Like

Idiot-proof doesn’t mean it can’t be broken.

2 Likes

Searching Google for “guava optional” gave me this really good wiki page on what Optional means.

Basically, as Java won’t throw an exception if you get a null value, null could be passed on to another method that cannot have null values. Worse, the null could be added to a Collection and not discovered until something iterates over it some time later.
If a method returns a type Optional<?>, the value must be retrieved by get() but it will throw an exception (IllegalStateException) there and then if it’s null. This should reduces the amount of possible weird errors and NPEs that could occur.

Extending on simon816, I have used Optioanl<?> in a team project recently and it really helps with early problem detection. It shortens the amount of times null is passed around so the error occurs much closer to the source. We generally pair it with code enforcement rules that require anyone receiving an Optional<?> to call .get() and not let it continued to be passed, and blocked methods from having Optional<?> as an argument.

Well mainly because it indicates that a method could return null in a MUCH more visible way than if we just write it in the javadocs. Think of how idiot-proof something can be if you are forced to handle the return value differently. Without some really stupid hacks (and even with those it would be pretty obvious) you can’t just ignore it when looking at code.

3 Likes

As said in Guava’s documentation, it is really useful for lookups, where null could be an error, or it could mean it doesn’t exist, or something else. Optional provides a more convenient way to reply to lookups: isPresent() means that it exists, and !isPresent() means that it doesn’t. Failure to follow the general contract supplied by Optional in favor of being lazy indicates a developer who still has much to learn about reading documentation. Also see http://stackoverflow.com/questions/3393341/what-would-we-do-without-null

And unsinkable doesn’t mean it can’t sink…

Exxxactly.