by valenterry · 3y ago · 0 comments
If a programming language supports union types and type inference then there is no need for such a "special" language feature as described here. The return type will simply have the form "goodresult | error" and the compiler will infer it based on the function-body alone.
At the same time, the following problem of zig is automatically a non-issue:
> A serious challenge with Zig's simple approach to errors that our errors are nothing more than enum values.
If the result is "goodresult | error" then I can choose of what type "error" is and I'm not bound to any predefined types that the language forces upon me.
In fact, the article then shows how to work around the issue with a tagged union. The problem is that this creates another issue: the composition of different error types.
E.g. having function foo calling bar and baz and bar can fail with barError and baz can fail with bazError. Then, without having to do anything, the compiler should infer that foo's return type should be "goodresult | barError | bazError". This won't work if tagged unions are used like in the example - they will have to be mapped by hand all the time, creating a lot of noise.
While Zig's errorhandling is not bad and miles above Go's, it makes me sad to see that we still lack ergonomy of errorhandling in so many languages despite knowing pretty much all of the language-features that are necessary to make it much easier.
The way Rust does it with its try operator (?), you have to tell it if it's barError (in which case it's up to you to tell it how bazError is convertible to it), or perhaps bazError, or something else altogether (e.g. sum type like you suggested, but conversion still needs to be supplied). There's also some libraries that provide error types for the lazy that are convertible from everything, so you can use try operator without much thinking, but for libraries you almost never use them.
Nothing stops you from defining certain "borders" in your application where you wrap errors into something meaningful. E.g. if I write a file-IO library, I will return a custom "CannotOpenFile" error in my public methods which will encapsulate the underlying error(s) instead of returning a list of potential low-level errors had caused it.
The difference is that with uniontypes it is me who decides the level of abstraction and granularity, whereas without it, I'm forced into manually handling errors types pretty much everywhere.
Rust is an example where you are always forced to either align error types or where you lose information about what kind of errors it could be by using a more abstract error type. (which is the last thing you mentioned)
The enormous number of Rust crates that attempt to automate various aspects of defining error types suggests that not everyone finds it so pleasant.
I'm 0% convinced that inferred return types are a feature that a production language should have, ever. I've used it before and it's infuriating on top of being bad code.
If a function is annotated f: T -> U where U is not an error, the contract with the caller is that f does not error, and cannot be changed to produce an error, and the compiler upholds this contract for all callers and definitions or redefinitions of f. It also means that another compilation unit can refer to f without having to type check its body, which sure, is a leaky abstraction, but empowers parallel compilation.
Changing the signature is a breaking change and as such should have a higher amount of friction. Changing the error type doubly so.
And on top of all that, errors should not be non discriminated union types. The example is Result<int, int> - you need the error to have a discriminant to distinguish between a success and an error code.
Why?
I'm all for very rigorous static type checking. But if we can make refactorings and changes frictionless — let's. Having the ability to move things around and reorder them to work better results in more iterations and better code.
As long as each iteration is very rigorously type-checked, of course.
However, most applications don't have any such exposure, all of their code is consumed internally. And even when they do, their external API surface which is actually exposed as some REST or ABI is minuscule in comparison to all the internal APIs — method calls and types that are never exposed anywhere.
I think that this problem, which is certainly a valid one, should be solved with methods which would not negatively affect developer experience of working with 99% of all the completely private APIs that don't need to be backwards compatible.
First, methods can (and often should) be annotated with their return types. And if a method is annotated as "T -> U" then it cannot return an error and trying to do so would fail the compilation - so I totally agree with you on that.
But inside of (non public) application or library code, there are a lot of small methods calling each other before there is some higher-up public method that will be called not by me but someone else.
And for those kind of methods type inference is great when it comes to refactoring. Even if I make a mistake and make such a method return an error even though it shouldn't, this mistake will be caught a bit higher up where the return type is annotated. In my experience this has almost no drawbacks and drastically simplifies refactorings.
Inferred return types don't make refactoring easier. In my experience they make it much more difficult, because you have to look at function implementation to understand what it does. Particularly for error handling, you always want to see what errors a function may return even in library code.
And all that said, there's no distinction to me between internals and externally facing code when it comes to quality and standards. If you have a function, even if it is called once, it should always have its return type annotated. It is more correct than leaving it to be inferred by the compiler, because you are explicitly annotating the intended behavior of the abstraction. This makes it easier to write correct code and for verifying it by a reviewer.
Any half-decent tooling should do that, since GP was talking about compile-time type inference. Of course there are some situations where the type hints aren't available, but then we're back to a general discussion about type inference.
FWIW, I don't actually agree with the idea that set-theoretic unions solve error handling, but I'm fully on-board with opt-in type inference for errors.
My editor/IDE does show the inferred type to me though. I don't have to look at the function implementation. If I had to, I would agree with you.
The OP is not suggesting that. They're suggesting that U can be an extensible union type that can be inferred from the code. Of course, if you declare it to not be such a union, then you guarantee no errors.
Just think of it like checked exceptions from Java, except the exception signature is inferred from the function's code. If you explicitly declare "does not throw", then the compiler produces a type error that you have not handled all exceptions.
I think the special language feature is the point, not an unfortunate side effect of something lacking in the language design.
The purpose of errors is to pass an indication of control-flow from the called function to the caller. That’s why the language has “catch”, “try”, “errdefer”, etc. This is about the language providing good flow control tools for the error path.
The problem errdefer solves is “resource passthrough” where a function needs to acquire a resource, do some faillible processing, and return the resource.
In case the processing fails, the resource needs to be released, which an unconditional “defer” is not great for (now you need extra flags).
But RAII solves the issue, in case of failure you just don’t return the resource, and it gets released. Likewise linear types, if you don’t return the resource you will have to explicitly release it.
Errdefer only adds a workaround, because now every time you acquire a resource you need to question how it interacts with the call stack and whether you need to defer or errdefer it, and any change to the function requires reconsidering this question.
Laughs in Go.
> While Zig's errorhandling is not bad and miles above Go's
Laughs again in Go. Go has no "foundations" regarding errors, it's just a convention. It has no union types. It doesn't have weird corner cases. It's just a returned value you can handle. Or not.
Of all the error handling paradigms I've seen, Go's requires the least amount of "specialized thinking" (try/catch or whatnot)--it's just becomes another variable.
If you want to just pattern match on type of visitor there is “another convenience helper” that you need to bring, and result still looks not pleasant.
Introduced in like c++17, even in c++23 you still need to write a std::visit to process it. Committee members waste time on yak shaving that std::print
So far I have never worked a Go project without a strict linter enabled on the pipeline checking that you handled the case when err != nil. I don't care if it is the compiler or the linter doing it, the end result in practice is that there actually is no chance of forgetting to check the error, and works just as well as a stronger type system while also making the code stupidly obvious to read.
A linter-based syntactic check is no substitute for a proper type system. A type system gives a machine checked proof. A heuristic catches some but not all failures to handle errors, it will also give false positives.
I remember a similar discussion here a couple months ago and some guy linking numerous open bug reports in Docker's repo with this very issue.
Sum types might be the 'mathematical dual of product types' but programming languages are not mathematics. The possibly implementations of sum types are quite varied. It makes sense in low-level languages for the programmer to use what makes sense in the particular situation.
> programming languages are not mathematics
This may be how you choose to view them. But many of us seeking to build safer and more correct software aim to make programming more like mathematics. Mathematics tells us how to compose and tells us how to prove. Both things the software industry is currently failing at.
[1]: https://github.com/vlang/v/blob/master/doc/docs.md#sum-types
I dunno, my IntelliJ calls out unhandled errors. I imagine go-vet does as well.
An alternative is to allow an additional parameter which optionally points to a diagnostics object to be updated upon error. Returning an error here signals that the object contains additional information while not harming composition as much and giving the choice of where to store such information. This is arguably a better pattern in a language where resource allocation is explicit.
Having errors as a first class construct in the language allows things like errdefer to be very simple and easy to use. It looks needlessly specialised at first, but I think it’s actually a really good design.
In those languages there are (or would be) generally two ways of achieving the same thing as errdefer:
1.) having a common interface/tag for errors
In that case, if you have a return type "success | error1 | error2" then error1 and error2 must implement a common global interface ("error") so that you can "chain" computations that have a return type of the shape of "success | error". "success | error1 | error2" would follow that shape because the type "error1 | error2" is then a subtype of "error".
2.) Having some kind of result type.
This would be similar to how it works in rust or in the example in the article here. So you would have a sumtype like "Result = either success A or failure B" and the errors that are stored in the result-failure (B) would then be uniontypes.
The chaining would then just be a function implemented on the result-type. This is personally what I use in Scala for my error handling.
Just to make it clear, this "chaining" is not specific for error-handling but a very general concept.
Well it could not be, and some would argue that would be better.
But you could also have a blessed type, or a more general concept of "abortion" which any type could be linked to.
Or you could have a different statement for failure returns that way you can distinguish a success and a failure without necessarily imposing a specific representation of those failures.
This cost may be necessary in manual memory management languages, where the vast majority of functions have to do some cleanup. There, having multiple exit points from a function through exceptions (or through early return statements) makes it harder to make sure all resources are properly cleaned up (especially when the cleanup of one resource can itself throw an error).
But in managed memory languages, there's just no reason to manually re-implement this pattern, either through Go style regular values or through sum types. And note that the Result monad is not a good substitute for exceptions, as it doesn't actually add the necessary context of what the code was doing when it hit an error case.
Sumtypes sure are useful, but I believe that except for GADTs, you can emulate sumtypes with uniontypes, but not vice versa.