4 ms·
My only contention with Optional<T> types as opposed to NULL/nil/null is that in practice they're almost useless. An Optional<T&> is a pointer, plain and simple
by moth-fuzz 4y ago
My only contention with Optional<T> types as opposed to NULL/nil/null is that in practice they're almost useless. An Optional<T&> is a pointer, plain and simple. If NULL is one of the expected values, it should be handled as expected. This leads to a vast simplification of a number of algorithms and data structures and no need for `.unwrap().unwrap().excpect("unreachable")` in the cases you can't do anything anyway. I've rarely seen cases where null values were possible at the algorithmic level, and expected, and not handled, because, lazy programmers I guess? Honestly all I can say for that particular case is that if you write half an algorithm, expect it to fail half the time...
On the other hand, if NULL is not an expected value, then how often do you really find the logic error at the same spot that the panic occurred? Not very often in my experience. We have callstacks for a reason. You usually find the NullPointerException at the bottom of the stacktrace or the None.panic() after 100-something other function calls in significantly complex codebases. No, if a function expects a value 100% of the time, and it was passed a NULL value, that's the caller's problem. And Option<T> won't help you if the user-facing calling code is still passing None or std::nullopt for whatever misguided or erroneous reason they may be doing so.
Certainly I agree there're benefits to encoding this kind of behaviour into the type system, but I don't agree that it's ultimately a solution to the '4 billion dollar mistake', since mistakes ultimately still happen. You just swap NULL for None and you still have a bug in your logic, just no longer a bug in the types. It's kicking the can.
- b3orn 4y agoIn C a pointer is a version of the optional type, implementing an explicit version of it is therefore pointless. In other languages you could enforce that a pointer can't be null or even forbid it to be uninitialized therefore you need to have an optional type for the cases where you want to allow null, so if you get a pointer you can trust it a little more.