When designing a null safe piece of code, what's the better approach?
F# and Scala has Options type that encapsulates null check, but we also have static code analysis tools like code contracts, findbugs.
To me static analysis seems a little cleaner, so what is the reason for Option/Maybe? In particular, what makes it better in preventing NullPointerExceptions/NullReferenceExceptions?
Option
is used to model the fact that computation maybe return a value. It doesn't exist merely to encapsulate null check; many functional programming languages such as SML, Haskell don't have null
but Option/Maybe
are present as useful tools for modeling problems.
To me static analysis seems a little cleaner, so what is the reason for Option/Maybe?
In the context of functional programming, using static analysis to check the absence of values is overkill. Static type checking can do it just fine (with Option
). And the type systems can guarantee absolute correctness while static analysis tools may have false positives.
Another problem with static analysis tools is high cost. It costs a lot to build them (I don't know any good static analysis tools for F# and Scala) and to use them (software purchase, developer training). Admittedly, they are powerful and should be used to catch more subtle errors (which can't be caught by static type checkers) such as index out of bounds, integer overflows, etc.