4 ms·
> How can you know that half the things I can represent are wrong? There are many situations where both returning a value and not returning a value are both val
by lmm 5y ago
> How can you know that half the things I can represent are wrong? There are many situations where both returning a value and not returning a value are both valid. And where errors conditions may not dictate what the returned value should be.
In cases where it's valid, you use a type that makes it valid. Much of the point of having a type system is that the return type tells you exactly what the valid things for the function to return are.
Having an explicit declaration of which functions might return both a result and an error and which functions will definitely return one or the other but not both makes your code easier to understand and work with. As it stands, I would bet that most Go programmers ignore the possibility of returning both a result and an error even in functions that do it deliberately, because the idiomatic thing a function with that signature does is return one or the other but not both.
- Huggernaut 5y agoI agree. I would be extremely surprised and look for refactoring opportunities if I came across a function that returned a success case that was expected to be used in combination with an error value. If anyone has an example of this being a pattern used somewhere that they think is good I'd love for them to share it.
- kadoban 5y agoThe only case I can think of is partial success. Probably bad example off the top of my head: You're returning say a "User" which has a user_id, name, and a list of recent purchases. If the function errors out on the recent purchases, the caller may prefer that it still gets back a "User" object with the other information filled in, and then an "error" also set so the caller knows the information isn't complete.
- xh-dude 5y agoA reduced version of this is maybe where Go and Rust have a pretty similar contract for things that “Read” and lean hard into permitting partial success. Both allow for some relatively sharp edge cases with zero-sized reads. The contract is always right … how well it is expressed through language mechanics is maybe another way to contrast things here. (FWIW I think Go could tighten up a few things - dropping or shadowing errors is a bit worrying - but I’m fairly convinced sum vs product is a little too harsh of a reduction; a useful distinction but not a complete one.)