2 ms·
From an ADT perspective, letting any type T be null is the same as saying everything is an Option<T>. Except nothing else in the language forces you to handle
by samatman 6y ago
From an ADT perspective, letting any type T be null is the same as saying everything is an Option<T>.
Except nothing else in the language forces you to handle the optional case, so you end up with either null checks everywhere, or your code blows up with NullPointerExceptions, or sometimes both.
Ever been deep in a Java call stack, and wondered if you've already checked for null in all cases? In a language with (only) Option types, you can simply declare that variable to be T, and if it's actually Option<T> (i.e. you haven't checked for absence along some path) you'll get an error. A good compiler will even tell you where in the code the None is sneaking in, so you can fix it there, or pattern-match on Some and None where the error is, depending on which is correct for your logic.
I'm ignoring the exceptions question, because the post doesn't even consider a condition/restart system, which means it's not-even-wrong.
- Graffur 6y agoWhy can't a compiler essentially do the same for null as you're describing for None?
- samatman 6y agoIt's basically a definitional thing. An Option type means you must specify Some (pointer) or could-be-None (null, NULL pointer) and the compiler will enforce the distinction. Generally this comes with exhaustive pattern matching, so you can turn Some<T> into <T>, and handle None by raising an error or assigning a default or blowing demons out your nose. None and null are the same thing, the name isn't the important part. Zig, for example, has optional types as ?*Foo, and calls the null pointer "null".