3 ms·
Option types represent computations that can fail. In order for an option type to be at all useful, you need to be able to actually do computations: take an Opt
by evincarofautumn 14y ago
Option types represent computations that can fail. In order for an option type to be at all useful, you need to be able to actually do computations: take an Option<A> and a function A → B, and get back an Option<B>. That’s exactly what the Functor, Applicative, and Monad instances for the Maybe type in Haskell do.
Here, you’ve just traded one kind of checking (!= null) for another (isDefined). This is more type-safe, to be sure, but has a high legibility cost. There is also no gain in exception safety: NoSuchElementException is not appreciably more meaningful than NullReferenceException.
- pcwalton 14y agoIn my experience the legibility cost is more than outweighed by the fact that Option is only used in a small set of places, rather than implicitly used everywhere as with nullable references. Because it's only used in a few places, the use of `.isDefined()` or pattern matching stands out and actually helps to make the reader aware of where computations could fail.
- evincarofautumn 14y agoSure, it’s certainly better to be explicit. I’m just saying that you can have explicit checked optionality and safety and legible code.
- kscaldef 14y agoYou should read part 2 of the post.