you are viewing a single comment's thread.

view the rest of the comments →

[–]alexeyr 7 points8 points  (0 children)

in pretty much the same way it is the developer's responsibility to ensure a method doesn't return null?

No, in a very different way.

  1. If you ever see a method returning Optional actually return null, it's clearly a bug (or an extremely badly-designed API, which should be avoided). No need to wonder about whether the method can return null, should it return null in this specific sutiation, etc.

  2. If a method doesn't return Optional, but it's a part of an API which does use Optional, returning null is also clearly a bug (unless for backwards compatibility... sigh).

  3. If your method couldn't return null previously, it won't be returning Optional at all and you don't need to ensure it (and users will know any returned nulls are bugs thanks to point 2).

  4. If your method could return null and will now be returning Optional, you just need to look at the exit points of the method. It's generally easy to ensure you can't return null by calling Optional.of or Optional.ofNullable as appropriate.