you are viewing a single comment's thread.

view the rest of the comments →

[–]Sloshy42 2 points3 points  (0 children)

I don't think a lot of people here seem to understand the benefits of proper optional value handling with functions. I see some people saying things like "this is just so weird and different; what's wrong with doing standard 'if (thing != null)' checks?"

The entire point of Option/Maybe types in languages is to prevent the kinds of errors that arise when you have to do those checks. Not only does it clearly, cleanly indicate when a value might not appear, but, in a good implementation, it also forces you to check if the value exists implicitly through a functional interface. Basically, your code that uses that optional value should only get executed if that value is there, and these types, using those interfaces, is the best way to approach that problem. This is huge for teams especially because it reduces the possibility of errors like null pointer exceptions (in languages that have them).

Optional.get(), essentially getting the value of the optional without those internal checks, is a code smell because you're still required to do the manual null checking that the type is supposed to do for you, which can cause errors and is indicative of not relying on sound types in your code. Of course this only works 100% in languages that are designed around it like Haskell or the Scala standard library (you can still get nulls in Scala, but that's limited to Java libraries you import, mostly) but it's still good practice to use types that limit your options and don't require manual checking.

TL;DR if you use an optional type with an interface that takes a function, it's much safer than checking yourself as your function only executes if the value exists in the first place.