null is dead, long live the new option! (java)

And the name of the new option is... Option! Empires come and go, null empire is about to be over. Some have thought of null to be some kind of a virus. If it was it was certainly one of the most successful spreading its null pointer exception all around the world. With that analogy you should think of Option as antivirus. You need to invest in it, install it, learn to use it, when its helpful sometimes its harmful use it for daily. Now back to programming language standard boring blog notation. You can create the concept of Option in java (or any other language of not existing) but its already in scala for the ones who have already converted.
Scala Option is not magic.
It does not solve somehow all your "non existing objects"!
the only thing it gives you is an explicit contract, meaning instead of some nulls hanging around in your code at runtime which may cause NullPointerExceptions you'll get Option hanging around in your code.
This is much better because of a function now does not return
def someMethod: String
but now returns
def someMethod: Option[String]

you are in a much better situation because now you know much better you need to check for "null" or in that option to check for None

so what you might do now is get the result of the method and do

result.getOrElse("empty")
this means you explicitly refer to the fact that no value has returned instead of getting somehow null and NPE.

Having said that, there are more options to handle Options, iterate (and the None shall be ignored) match them, and more, so the bottom line is that its a little more clearer what to do with empty values.

thanks

Comments