0

I came across Optionals recently in Java 8( A bit late yes). and I dont understand what is so special about them. The official documentation does say that it makes your code more readable and protects it against null pointer exceptions. Consider the following example.

Suppose, we have a method called getString() which ofcourse returns a string and we store in a variable called sample.

           String sample=getString()

Now, if we do the following-

          Optional<String> stringOptional=Optional.of(sample)

and sample is null, the above statement will throw a null pointer exception. Suppose, we use another method of Optional i.e.

           Optional<String> stringOptional=Optional.ofNullable(sample)

We will still need to check that

          if(stringOptional.isPresent())

I dont understand and am not convinced, how is the above better than doing directly

          if(sample!=null)

I know this question is purely opinion based, but would appreciate if someone points out and gives a good example of why optionals are a good addition to java and help developers not to write boiler-plate code.

Indraneel Bende
  • 3,196
  • 4
  • 24
  • 36
  • `Optional.of(sample)`, if `null` is good since it moves the exception to an earlier point than before. In the worst case it could be that a `null` value wanders around your program, undetected since no branch hits it. You always want to move exceptions and bugs to the earliest possible point, that's why we prefer compile time errors over runtime exceptions. – Zabuzard Mar 10 '18 at 01:50
  • Another good opportunity for `Optional` are `Stream`s. The where developed for `Stream`s as main usage. You can then easily cascade methods using optional, since `null`-checks in streams are super unhandy. – Zabuzard Mar 10 '18 at 01:51
  • You may take a look at [Optional - The Mother of All Bikesheds by Stuart Marks](https://www.youtube.com/watch?v=Ej0sss6cq14). A talk by one of the Java guys. He explains the class, its usage, advantages and disadvantages, misunderstandings etc. in detail. – Zabuzard Mar 10 '18 at 01:55

0 Answers0