How are we supposed to deal with null values though? It’s an important concept that we can’t eliminate without losing information and context about our data.
0 and “” (empty string/char) are very often not equivalent to null in my use cases and mean different things than it when I encounter them.
You could use special arbitrary values to indicate invalid data, but at that point you’re just doing null with extra steps right?
I’m really lost as to how the concept isn’t neccessary.
I’ll point to how many functional languages handle it. You create a type Maybe a
, where a
can be whatever type you wish. The maybe type can either be Just x
or Nothing
, where x
is a value of type a
(usually the result). You can’t access the x
value through Maybe
: if you want to get the value inside the Maybe
, you’ll have to handle both a case where we have a value(Just x
) and don’t(Nothing
). Alternatively, you could just pass this value through, “assuming” you have a value throughout, and return the result in another Maybe
, where you’ll either return the result through a Just
or a Nothing
. These are just some ways we can use Maybe
types to completely replace nulls. The biggest benefit is that it forces you to handle the case where Maybe
is Nothing
: with null, it’s easy to forget. Even in languages like Zig, the Maybe
type is present, just hiding under a different guise.
If this explanation didn’t really make sense, that’s fine, perhaps the Rust Book can explain it better. If you’re willing to get your hands dirty with a little bit of Rust, I find this guide to also be quite nice.
TLDR: The Maybe
monad is a much better alternative to nulls.
Isn’t a Maybe enum equivalent to just using a return value of, for example, int | null
with type warnings?
Not quite, because the Maybe enum is neither int nor null, but it’s own, third thing. So before you can do any operations with the return value, you need to handle both cases that could occur
you could take a look at what Rust is doing with the Option enum. Superficially it looks similar to using null, but it actually accomplishes something very different.
A function that classically would return a value, say an int, but sometimes returns null instead, becomes a function that returns an Option. This forces explicit handling of the two cases, namely Some(value) or None. This way, it is next to impossible to try to do an operation on a value that does not exist.