4 ms·
in reply to cookiemonster11, the wrong part is that it doesn't work well. When you asked for exceptions you actually wanted an Either type, which means the fun
by spion 12y ago
in reply to cookiemonster11, the wrong part is that it doesn't work well.
When you asked for exceptions you actually wanted an Either type, which means the function either return a result or an error (not both).
You also want something that propagates errors automatically (the monadic bind) in case you don't want to check every result.
An Either type lets you get the best of both worlds. It lets you model exactly whether an error can or cannot happen (unlike exceptions that are not optional). It lets you check every return value directly via pattern matching (similarly to Go) but also, the compiler will warn you if you "forget" to handle the error case. Finally, the bind operator lets you chain operations in a way that only executes in case of no errors, plus attach a single error handler at the end to handle any of the errors (in a manner similar to exceptions)
So yeah, there are better solutions today.
- TheLoneWolfling 12y agoHow I wish nullable types worked in C-like languages: You cannot dereference a nullable value normally. However, inside a (x != null) block, or rather anywhere the compiler can infer that the value cannot be null, it automagicially turns into a non-nullable type. And there's the null-safe dereference operator (.? or similar) that returns null in case the first value is null. Similarly with casting - if you have an if block with an instanceof check, within that block the variable has the type given by the check. You still have to have a runtime-checked NPE in some cases (in case of hotswapping, casting to non-nullable types (which should be allowed but throws a checked excption), etc), but mostly this avoids the issues with NPEs, I think. I agree that pattern matching can be powerful, and underutilized in most language designs. Alternatively, I've been growing more in favor of the idea of not having null at all in the base language - if you actually need it it's relatively easy to implement if you have boolean algebra on types (Nullable<x> being equivalent to Either<x, Null>, where Null is an enumerated type with one value, null. Like what you said). And that way it's explicit, and people are more likely to use a better (read: more informative) exception type). Null ends up being an exception with no additional information, which can work in some cases, but often you want additional information. Even just "NotInitialized" or something like that is often better.