2

I have been asked to prefer using Optional class to avoid null pointer exception but I am not sure how will it help dramatically, as anyway we still have to apply a check optional.isPresent() to avoid getting exception just like null check.

I don't see that it's very useful unless we use optional.or() to override with some default value or most of the time with an empty object.

Is there any other benefit, which I am missing to see, otherwise this can be easily avoided without getting any extra overhead?

krmanish007
  • 6,749
  • 16
  • 58
  • 100
  • 1
    By returning optional from your method, you force your client to perform explicit check. – slnowak Dec 16 '14 at 16:32
  • But I can still call optional.get() without checking and it will throw IllegalStateException instead of NullPointerException! – krmanish007 Dec 16 '14 at 16:33
  • 1
    But the fact that you have to call `get` at all is a reminder that you should check `isPresent`. Without `Optional` you are more likely to just code along assuming everything is fine when it may not be. – Ian McLaird Dec 16 '14 at 16:36
  • http://marxsoftware.blogspot.in/2011/10/guavas-new-optional-class.html – Trying Dec 16 '14 at 16:41

1 Answers1

4

By returning optional from your method, you force your client to perform explicit check agains absent value.

As long as you are the only one who uses your method and your remember about null-check, everything is fine.

But now suppose I'm using your API - how can I know, whether your method could return null or not? Without reading javadoc of course. If I saw Optional as a return type, I know exactly that such situation could happen and I can react.

slnowak
  • 1,839
  • 3
  • 23
  • 37