3

I don't understand the usability of optionals. For example, why not initialize a string to null? Can someone explain what is so revolutionary about them? It seems that they have been hiding within the language for a while now.

Malik Brahimi
  • 16,341
  • 7
  • 39
  • 70

1 Answers1

0

They actually have been implemented in Java 8 so they actually haven't been "hiding" very long. But Google Guava had them for some time, and the Guava guide provides a very compelling analysis on why to use them.

https://code.google.com/p/guava-libraries/wiki/UsingAndAvoidingNullExplained

Nulls suck because they are difficult to determine if they are deliberately used for a design or not. Optional forces the developer to address the idea of an absent value and check for it first.

Not to mention, the Java 8 Optional has some very powerful lambda methods, like map(), flatMap(), and filter() which streamline a chain of transformative operations on a possibly empty value without risking a null pointer exception.

There really is no good reason to use null in your designs unless you're doing some performance-intensive process. Otherwise you are just subjecting yourself to NullPointerExceptions.

tmn
  • 11,121
  • 15
  • 56
  • 112