No stacktraces and error wrapping forces you to not only invent unique error messages. You must also conceive a unique wrapping message at every call-site so that you can grep the error message and approximate a stacktrace.
The weird "return tuple" , which obviously just exists for errors because there is not a single other place where you can use tuples in the language, and the awkward variable initialization rules, make it so that you use the wrong `err` var at some point. E.g. if you want to reassign the result to an existing var, suddenly you have to declare `var err error`, and if `err` already exists then you have to reuse it.
There should be an enum type in go, or instead of the bizarre "return tuple" mechanics exclusive for errors, they should have added a better syntax sugar for errors like rust's `?` sugar. Instead we have something extremely tedious and quite error prone.
> it has a lot of build in opinions which protect you from yourself
It does have opinions, but too often they seem to be there to protect the language from being criticized. Sadly, this works, as marketing (lying) is an important factor towards making a PL popular in today's market.
They are so different in DX, ergonomics, implementation and traceability that I'm not sure this is true other than in the most abstract sense
Because the compiler will fail if you don't explicitly mention each possible exception.
But checked exceptions are coming out of style: They're unchecked in C#, and frameworks like Spring Boot in Java catch all checked exceptions and rethrow them as Spring Boot flavored unchecked ones.
For unchecked exceptions and Result types:
The DX is very different in one critical way:
With Results you constantly have to differentiate between error and ok states, before you proceed. With unchecked exceptions you generally assume you're always in an ok state. It's equivalent to wrapping your whole function body in 'try { ... } catch (Exception e)'. And you can get that with Result types in Rust by using '?' and not worry about doing something half-way.
Ultimately: Are you a happy-path programmer?
But only the first time. Once you add `throws FooException` to the caller signature, the compiler won't complain about any future callees that also happen to throw FooException, even if you did care about handling their exceptions yourself. With callees that return Result you do get to make that decision for every callee.
I would say "adding Result to the caller signature" provides a similar cascade, but it's not entirely true: Every call must separately be unwrapped. So consistently wrapping your Result calls with the '?' operator is similar to a gigantic try-catch block or adding 'throws CheckedException' everywhere.
So both the '?' operator and adding 'throws CheckedException' everywhere let you accidentally neglect proper error handling: You have a default that is syntactically almost invisible and frees you from thinking. The checked exceptions give you a little more freedom from thinking than the '?' operator.
No. You're choosing to write the `?` there to bubble up the error. It's a compiler error if you forget it. Whereas with `throws FooException` you only get forced to remember it the first time, and after that you're allowed to forget it.
...but you're not choosing to write the `throws FooException`?
I can only say that if the `?` weren't around and you had to write more verbose handling each time, having the question "How should this one particular error be handled?" might come up more often and might prevent more bugs than when you can carelessly `?`-annotate your way through a dozen lines without any equivalents of `finally { ... }` anywhere.
Now read the rest of the comment after where you stopped reading. Or reread https://news.ycombinator.com/item?id=42249525 I'm tired of repeating myself.
MRV, go does not have tuples.
Go is not the only language with MRV (as a special case) and they’re not necessarily bad, iirc Common Lisp uses them as auxiliary data channels and has a whole host of functions to manipulate and refit them.
Go is singularly incompetent at MRVs though, in the sense that only syntax and builtin functions get access to variable arity (e.g. if you access a map entry you can either get one return which is a value, or two which are the value and whether the key is/was in the map). So MRVs mostly end up being worse tuples infecting everything (e.g. iterators needing Iter and Iter2 because you can’t just yield tuples to for loops).
> MRVs mostly end up being worse tuples
I think you noticed yourself that you’re getting too hung up on terminology. Multiple return values are a half-hearted, non-reified version of tuples.
Acronym for Multiple Return Values https://gobyexample.com/multiple-return-values
It's a plus versus minus type of situation, where both have their advantages and disadvantages, along with a number of workarounds and alternatives that can be used.
In many cases, people can return arrays, hash maps, or structs in place of tuples. That looks like the reasoning in Go, where if the person needs something beyond MRV, they can use the other options available. Go and various other languages, didn't need or didn't want to lean on tuples as much.
The problem is that Go only has the drawbacks of MRV and leverages essentially none of the advantages.
> Go and various other languages, didn't need or didn't want to lean on tuples as much.
As far as I’m concerned go would be a strictly better language if it had tuples (or even just the ability to unpack structs).
All the nonsense about foo/foo2 to handle both single and multiple results would go away, and pretty much the only thing which would be lost is individual addressing of MRVs for named return values, which is easy enough to replace by naming the return struct and going through it.
The tenet "accept interfaces, return structs" is violated all over by returning the `error` interface.
IMO it's okay to make behaviour-exceptions specifically for error handling. Rust for example doesn't really have builtin behaviour exceptions specifically for errors, they're generic to sumtypes and just happen to work well for errors. But then in practice you must resort to thiserror or anyhow helper crates to deal with errors in anything but tiny programs.
If you do make behaviour exceptions for error handling, be honest and upfront about it. Don't say "errors are just values so just use them like regular vars" in docs, if then there are several huge exceptions (tuple-returns and breaking a core tenet). If you make exceptions then you might as well do them right, instead of half-assing them. I believe zig does it right, but I haven't gotten around to try it.
To be fair, that expression came from a blogger who often wrote about Go. It is not a tenet held by the Go project. In fact, Rob Pike has made clear that he considers it to be misguided advice. It is only violated in the same way returning Result in Rust violates the assertion I made up for this comment: Do not return Result.
error is implemented by types all over the standard library and beyond and consumed by functions that wrap errors in the errors package. It's exactly an example of what you claim is violated.
Even more obviously your link isn't talking about functions but packages. There are some violations out there but generally when included packages define interfaces they are ones that get consumed like in io or it's dissolution.
It's in the first paragraph. It goes on in the second:
> Do not define interfaces on the implementor side of an API “for mocking”; instead, design the API so that it can be tested using the public API of the real implementation.
And yes, io.Reader/Writer violate that too, because either the tenet is wrong or the design of interfaces in go is wrong.
> Even more obviously your link isn't talking about functions but packages.
It doesn't matter: your exporting errors behind the error interface, not your concrete error implementation. If you're just using one of the many ways to create stringly errors (!) like fmt.Errorf, you maybe don't notice but you are in fact returning interfaces all the time.
> This page collects common comments made during reviews of Go code, so that a single detailed explanation can be referred to by shorthands. This is a laundry list of common style issues, not a comprehensive style guide.
The document does not assert that you must not return interfaces or that it is incorrect to return interfaces, only that returning interfaces at inappropriate times has been a recurring issue found during code review. Sometimes returning an interface truly is the right choice, but when it isn't...
Like most adages in programming, the aforementioned tenet holds validity in many cases, but, as always, "use your noggin" applies.
It also matters what the io package actually does. https://pkg.go.dev/io . The io package has a very limited number of functions that return Readers. The vast majority of its functions take Readers or Writers as arguments and do useful things with them: e.g. Copy or LimitedReader. Most of the interfaces it defines (ReedSeeker, ReadWriteSeeker, etc) aren't instantiated by anything in it.
os implements Reader and Writer for filehandles. net does the same for sockets etc.
I'm not arguing that the tenet should be held true, to be clear. I'm saying that this tenet is misleading. If you can, return a concrete type. If several packages consume the same interface, then you it's not reasonable to define the interface at the consumer because you'd just have to copypaste it.
Doesn't that go without saying? There is no tenet that isn't misleading when presented to a general audience. Fair that if you come from a position where you understand the full context and nuance under which the tenet was built then you should be able to free yourself from being mislead, but, of course, this time is no exception.
> If several packages consume the same interface, then you it's not reasonable to define the interface at the consumer because you'd just have to copypaste it.
Where several packages find interface commonality, there is no doubt a set of "primary" functions that roll up shared functionality around that interface. The package of shared functions is understood to be the consumer under that scenario.
Where several packages stumbled upon the same interface without any shared functionality, copy/pasting is warranted. In this case, while the interfaces may look the same, they do not carry the same intent and that needs to be communicated. Another oft-misunderstood tenet, do not repeat yourself, does not imply avoid repetitive code.
I can give you a concrete example.
I have a "storage" package, that exports multiple storage implementations/backends. Files, in-memory, S3, zip...
Some other packages pick one of the implementations to instantiate, depending on the use case (this is NOT a case of mocking for testing or anything like that).
Most other packages work with a "storage" interface, as they're only concerned with reading/writing to "storage".
So the storage package, or in any case some package, has to export the interface. Otherwise, every consuming package would have to copypaste that interface, which is NOT warranted.
An additional package would export the interface and provide the common functionality around that interface. Those common functions would be considered the consumer. In fact, the standard library offers an example of exactly this: io/fs.
Yes, you have technically moved the interface type away from the implementation, but just for the sake of it, without any other upsides. The consumer is still the package that is using and importing this interface type, just from another package now.
But, this is the "idiomatic" approach. The upside is consistency for future readers. Code is for humans to read, after all. Most codebases follow this pattern, so it will be familiar when the next person encounters it. If you have a reason to do things differently, go for it. Nobody knows your problem better than you, so you cannot listen to others anyway.
I am quite curious about what you see in the different tradeoffs you are accepting, though! What has you weighing them in favour?
All libraries that I recall ever using always export a single package, including interfaces. I just took a look, and even io exports a bunch of structs along the interfaces they implement. And `error` is like a basic type of the runtime.
The standard library provides examples, including a "storage" example.
> All libraries that I recall ever using always export a single package
And now there are questions around the language being spoken, so to speak. That's the power of idioms – it avoids the reader needing to ask questions when encountering language that is new to them. But idioms are not the be all, end all. Sometimes they just don't fit. And if that's the case in your situation, no problem. Nobody knows your problems better than you. To listen to someone else tell you how to solve your own problems is foolish.
That is why I earlier wished we had seen some real code. Perhaps then we would understand the nuance that has lead to you choosing these particular tradeoffs. We have no sense of what problems you are actually trying to solve, and questions to try and glean greater insight have been left unanswered. As a rule, though, an overarching interface package with consumptor functions along with multiple implementation packages is preferable because then it avoids a lot of the questions developers are going to start asking.
For example, with the alternative suggested, what if I want to add a new storage adapter that conforms to your interface? Do I need commit rights to your package or should I create my own package that satisfies your exported interface? If I create my own package, why is it the lone implementation in its own package while the others are all rolled up in one package? Is it that you don't want third-party implementations for other services not covered by your package? Why is that? On and on...
If you stick to the idioms, those questions are already answered by convention.
Go functions also accept a tuple on input. While theoretically you could pass an error, or a pointer to an error for assignment, it is a stretch to claim it is for errors.
There is a nice func Must(value, err) { if err { panic(err) } else { return value } that you can use in tests to get around the inane regular error handling. But that's about it, to my knowledge. Sad that there isn't more to it. If literally everything returns error as last return value, there could well be some syntax sugar there.
Like I mentioned in another comment, Go does seem especially prone to attracting developers familiar with other languages who insist on trying to continue to program in those other languages even after working in a Go codebase. That may create a condition whereby the developers you regularly come across don't have a good grasp of where to use multiple return arguments effectively, and thus end up avoiding them, even where they would be appropriate.
With respect to the syntax sugar, there have been a number of proposals for exactly that. While the proposed syntax itself has been well received, nobody has come up with a good solution for the rest of the problem. Syntax is only about 10% of what is needed, of course. Rust, for example, has well defined traits and other features to go along with its '?' operator to fill in the remaining 90%. Presumably there is a good solution out there for Go too, but until someone proposes it...
If the language doesn't have tuples, then you have to "roll your own" and emulate them every single time, but it's not a functor so you can't do all the useful stuff.
Go didn't do the pragmatically right choice, because it's only right from a type perspective. But go doesn't care about types at all, they're just a side effect. Go only needed to return multiple values, so that you don't have to pass in one (or more) "out" pointer as argument, and check an errnum. So go is right but only from its narrow perspective: it's better than C.
Perhaps, but in practice we end up with these ill-conceived languages that support tuples but end up not embracing them. Consider, for example, this Rust function:
fn process_tuples(tuple1: (i32, i32), tuple2: (i32, i32), tuple3: (i32, i32))
If it made the "right" choice a function would only accept a single input value, which could be a tuple: fn process_tuples(tuples: ((i32, i32), (i32, i32), (i32, i32)))
But maybe that's not actually the "right" choice? What if there is a pragmatic reason for functions to have their own concept for tuples that is outside of a tuple type? I will admit, I would rather work with the former function even if it is theoretically unsound. It does a much better job of communicating intent, in my opinion.And once you accept the theoretical unsoundness of a function having its own tuple concept for input, it naturally follows that it needs to also extend that concept to returns. After all, the most basic function is an identity function. What would be super weird is not being able to write an identity function any time the number of inputs is greater than one.
Go needed to allow multiple outputs because functions can accept multiple inputs.
I don't think that's the right conclusion, unless you have any source or insight?
It would explain why you can directly cast the multi-return-values into parameters when calling, but... that doesn't seem to fit go at all.
What I would think is that "go needed multi-return to be able to return errors along values", and the mentioned feature is just some vestige. It's not like go ever implements anything for the sake of consistency or correctness.
It is the "right" conclusion in general. Multiple input arguments without multiple output arguments is frustratingly awkward. I can understand the appeal of your suggestion of only accepting one input and returning one output, where the passed value might be a tuple, but I expect there is good, pragmatic reason why virtually no languages, even those with a proper tuple type, haven't gone down that road. Once a language accepts multiple arguments, though, it needs them in and out. Otherwise you can't even write an identity function. If you can't write an identity function, is it even a function?
> "go needed multi-return to be able to return errors along values"
If there was some specific reason for its addition, beyond the simple fact that it would be crazy not to, it was no doubt for map presence checks. Without that, it is impossible to know if a map contains a given key. Errors can be dealt with in other ways. It wouldn't strictly be needed for that purpose, although it turns out that it also works for that purpose, along with a whole lot of other purposes. Not to mention that we know that the error type was a late-stage addition, so there is strong evidence that errors weren't a priority consideration in the language design.
> it was no doubt for map presence checks. Without that, it is impossible to know if a map contains a given key
Are you just making stuff up on the go? A map access is not even a function call. And if you need a presence check in the early language development stage, it's much simpler to add support to check presence and then get the value, since it's not threadsafe anyway.
That remains the most reasonable explanation. There is no legitimate reason for functions that accept multiple arguments but only return one argument. That defies the very nature of what a function is.
C made a mistake, but that is not a good reason to copy it. It also made a mistake around memory management. You wouldn't copy that in a modern language either, would you?
> A map access is not even a function call.
Theoretically it is, albeit with unique syntax. However, importantly, it establishes the concept of multiple returns in the language. Once the syntax for multiple returns is worked out, there is no reason to not extend that to functions proper.
But the most likely reason it was added was not because of some specific reason, but because it would be strange without. It is not like Go is the only language that has that feature. It was already an accepted paradigm.
I refuse to believe that go added MRV for some esoteric reason. In practice it just makes up for the lack of tuples and sumtypes (errors mostly). It also would stand sharply against every other design decision (or accident) that go has made.
MRV also lacks functors in contrast to tuples.
I agree that Go should really have an analogue to Rust's `?`, but you can't really do that in a sane way without sum types to represent your conditions. The very multiple-return style error propagation makes it impractical to do.
IMO Go should add really basic tagged unions and rework the stdlib to use them, but such a change would probably necessitate a v2.
You must mean the language? They said that a language v2 (go2) is probably unnecessary – that any future additions could be added without breaking the existing language. I don't expect simple tagged unions would need to break anything. A v2 (or even v3, perhaps) stdlib would be necessary to take advantage, like the parent suggests, but that has never been ruled out and is already the status quo.
I admit I have no idea.
Thanks for clarifying, that makes sense.
It could be just some simple (hey, that's what go wants to be, right?) macro thing, that just does the everyday `if err!=nil{return ..., err}` for you without having to juggle (and think about) vars.
b := g(f()?)?
// var b B
// {
// var a A
// var err error
// a, err = f()
// if err != nil {
// return *new(A), *new(B), err
// }
// var b B
// b, err = g(a)
// if err != nil {
// return *new(A), *new(B), err
// }
// // no accidental reuse of err
// }
I mean look how much utterly useless noise this is, and count all the opportunities for mistakes that wouldn't get caught by the compiler.Therefore other languages (influenced by Golang), like V (vlang.io), Odin (odin-lang.org), Jai, C3... made such improvements. One could argue that it's more a matter of if people are going to be brave or open-minded enough to try something different or go in a different direction.
There is always the Odin style 'or_return' operator, which is defined for a similar situation.
[1]: https://vlang.io/
[2]: https://github.com/vlang/v/blob/master/doc/docs.md#optionres...
[3]: https://github.com/vlang/v/blob/master/doc/docs.md#sum-types
[4]: https://github.com/vlang/v/blob/master/doc/docs.md#returning...
There was a proposal for a `try`, which I still think should have been adopted.
Under that proposal, `someComplicatedExpression(try(functionReturningError()))` would be converted to `foo, err := functionReturningError(); if err != nil{return zeroValue, zeroValue, err}; someComplicatedExpression(foo)`
I'm not sure I would be satisfied with any implementation of try as the language is now, I assume the Go language team would probably feel the same.
Looking at Alef, apart from using tuples to provide multiple return values in a C-like language, they don't seem to actually add much functionality over what Go has without them. One of the few extra things is the ability to pass a tuple over a channel, however passing a struct is more or less equivalent.
I've not looked in much detail at what Limbo could do with its tuples.
So maybe they don't really add that much, hence why they were not carried over when Go was created?
Alef had enums, Limbo has something like the Go constant scheme and iota. Limbo also had tagged unions / varient-records, in a sort of Pascal like fashion - the "pick adt".
Where I agree: It forces you to think about all of the possibilities your code might generate. (This is more of a C question than it is with other languages)
However, when abstracting blocks of code away, you don't always need to handle the error immediently or you may want to handle it down the stack.
You're giving up a lot of readability in order for the language to be particular.
Error handling is still explicit, but it gives you the tools needed to make it less tedious.
Except it doesn't actually. You can totally just ignore it and pretend errors don't exist. Lack of sum types/Result, and pointers as poor mans optional, really hinder's Go's error handling story.
The coding style encourages the behavior you're talking about. We're back in the C days where you have a result and an error. It's not a good pattern.
I’ve seen way too much Go code which never even tested the err value to believe that until something like errcheck is built in to the compiler.
I do agree that this is a plus for the explicit model but that’s been a better argument for Rust in my experience since there’s better culture and tooling around actually checking errors. I’m sure there are plenty of teams doing a good job here, but it always felt like the one lesson from C they didn’t learn well enough, probably because a language created by experts working at a place with a strong culture of review doesn’t really account for the other 99% of developers.
They are just horrific gotos that any library can invoke against your code. They are pretty much never, ever handled correctly. And nearly always, after an exception is “handled”, the application is actually in an unknown state and cannot be reasoned about.
Even junior engineers have a trivial time debugging most go errors, while even experienced principles struggle with figuring out the true cause of a Java exception.
Once every return is a Result, every call a ?, and every error a yeet, what's the difference between your program and one with exceptions except the Result program being syntactically noisy and full of footguns?
Better for a language to be exceptional from the start. Most code can fail, so fallibility should be the default. The proper response to failure is usually propagating it up the stack, so that should be the default too.
What do you get? Exceptions.
It means you can use things like result.map_err(|e| …) to transform an error from one type to another. (Though if there’s a suitable From conversion, and you’re going to return it, you can just write ?.)
It means you can use option.ok_or(error) or option.ok_or_else(|| error) to convert a Some(T) into an Ok(T) and a None into an Err(E).
It means you can .collect() an iterator of Result<T, E> into a Vec<Result<T, E>>, or (one of the more spectacular examples) a Result<Vec<T>, E> which is either Ok(items) or Err(first_error).
It’s rather like I found expression-orientation, when I came to Rust from Python: at first I thought it a gimmick that didn’t actually change much, just let you omit the `return` keyword or so. But now, I’m always disappointed when I work in Python or JavaScript because statement-orientation is so limiting, and so much worse.¹ Similarly, from the outside you might not see the differences between exceptions and Rust-style Result-and-? handling, but I assure you, if you lean into it, it’s hard to go back.
—⁂—
¹ I still kinda like Python, but it really painted itself into a corner, and I’ve become convinced that it chose the wrong corner in various important ways, ways that made total sense at the time, but our understanding of programming and software engineering has improved and no new general-purpose language should make such choices any more. It’s local-maximum sort of stuff.
As usual, I find that opposition to exceptions is rooted in a misunderstanding of what exceptions really are
Perhaps this also might be clearer: the fuss is not about the errors themselves being values, but about the entire error handling system being just values.
With exceptions they are thrown and end up somewhere else in a catch block, so the path of the success value is now distinct from the path of the error value.
Because errors as values are explicit. You're not forced to use ? everywhere; you can still process errors however you like, or return them directly to the calling function so they deal with it. They're not separate control flow like exceptions, and they're not a mess like Go's.
Yeah, yeah, you can say it's explicit and you can handle it how you want and so on, but the overall effect is just a noisy spelling of exceptions with more runtime overhead and fewer features.
In closed-world, system-software, or low-level software you want to have your kind of knowledge about everything you call. Even more: can it block?
In open-world, business-software, or high-level software it is often impossible or impractical to know all the ways in which a function or method can fail. What you need then, is a broad classification of errors or exception in the following two dimensions: 1. transient or permanent, 2. domain or technical. Those four categories are most of the time enough to know whether to return a 4xx or 5xx error or to retry in a moment or to write something into a log where a human will find it. Here, unchecked exceptions are hugely beneficial. Coincidentally, that is the domain of most Java software.
Of course, these two groups of software systems are not distinct, there is a grey area in the middle.
That's why it's often considered one of the better approaches: it has both the "errors as values" benefits (encoding errors in the type system) and avoids many of its problems (verbosity when you just want to bubble up).
...Or solve the problem. A library function that can be a source of issues and can't fix these issues locally should simply not be returning something that is not a result in that paradigm.
> since something can go wrong in most code
That is not my experience. Separating e.g. business logic which can be described cleanly and e.g. API calls which don't is a clear improvement of a codebase.
> the whole codebase converges as time goes to infinity on having Result everywhere.
As I said previously, it is pretty easy to pipe a result value into a function that requires a non-result as input. This means your pure functions don't need to be colored.
People "solve" this problem by swallowing errors (if you're lucky, logging them) or by just panicking. It's the same problem that checked exceptions in Java have: the error type being part of the signature constrains implementation flexibility.
I'd be curious to see examples for where you think Rust is still to verbose.
Kotlin isn't relevant here because all exceptions are unchecked.
Function coloring isnt a problem, it is just approach
• they may propagate automatically from any point in code, potentially breaking atomicity invariants and preventing forward progress, and have to be caught to be transformed or wrapped – Result requires an explicit operator for propagation and enables restoring invariants and transforming the error before it is propagated.
• they are an implicit side-channel treated in the type system like an afterthought and at best opt-out (e.g. "noexcept") – Result is opt-in, visible in the return type, and a regular type like any other, so improvements to type system machinery apply to Result automatically.
• try…catch is a non-expression statement, which means errors often cannot be pinpointed to a particular sub-expression – Result is a value like any other, and can be manipulated by match expressions in the exact place you obtain it.
Sure, if you syntactically transform code in an exception-based language into Rust you won’t see a difference – but the point is to avoid structuring the code that way in the first place.
A failure can propagate in the same circumstances in a Rust program. First, Rust has panics, which are exceptions. Second, if any function you call returns Result, and if propagate any error to your caller with ?, you have the same from-anywhere control flow you're complaining about above.
Programmers who can't maintain invariants in exceptional code can't maintain them at all.
> try…catch is a non-expression statement,
That's a language design choice. Some languages, like Common Lisp, have a catch that's also an expression. So what?
> they are an implicit side-channel treated in the type system like an afterthought an
Non-specific criticism. If your complaint is that exceptions don't appear in function signatures, you can design a language in which they do. The mechanism is called "checked exceptions"
Amazing to me that the same people will laud Result because it lifts errors into signatures in Rust but hate checked exceptions because they lift errors into signatures in Java.
Besides, in the real world, junior Rust programmers (and some senior ones who should be ashamed of themselves) just .unwrap().unwrap().unwrap(). I can abort on error in C too, LOL.
What do you consider failure? A result or a panic? Those are worlds apart.
> First, Rust has panics, which are exceptions.
That's not how exceptions work in Java. Exceptions are meant to be caught (albeit rarely). Panics are meant to crash your program. They represent a violation of invariants that uphold the Safety checks.
Only in extreme cases (iirc Linux kernel maintainers) was there a push to be able to either "catch panics" or offer a fallible version of many Rust operations.
The Rust version of Java Exceptions are Results. And they are "checked" by default. That said, Exceptions in Java are huge, require gathering info and slow as molases compared to returning a value (granted you can do some smelly things like raising static exceptions)[1].
[1] https://shipilev.net/blog/2014/exceptional-performance/
> Non-specific criticism. If your complaint is that exceptions don't appear in function signatures, you can design a language in which they do. The mechanism is called "checked exceptions"
And everyone hates checked exceptions. Because rather than having a nice pipe that encapsulates errors like Result, you list every minute Exception possible, which, if we followed the mantra of "every exception is a checked exception" would make, for example, Java signatures into an epic rivaling Iliad.
> Besides, in the real world, junior Rust programmers (and some senior ones who should be ashamed of themselves) just .unwrap().unwrap().unwrap().
If this is a game who can write worse code, you'll never find Java wanting. As a senior Java dev, I've seen things... Drinking helps, but the horrors remain.
Panics are fatal errors that the program is not expected to recover from, and it might as well terminate on the spot – as if you cut off power, which you have to be ready for no matter what. In fact, abort-on-sight-without-unwinding is one of the ways they can be configured to work. It’s the case where an operation fails, but the program attempts to continue running that is the most fragile. This is where you’re likely to enter an invalid state.
> you have the same from-anywhere control flow you're complaining about above
Not from literally anywhere – from the places where the error-propagation operator is used. I will never have myself thinking “oh wait, F could have thrown before G is invoked and break my invariants!” months after writing that code. C++ is chock-full of such problems: https://www.youtube.com/watch?v=b9ZYM0d6htg
> Some languages, like Common Lisp, have a catch that's also an expression. So what?
So more power to them! That is actually a major improvement compared to your typical dynamic ALGOL, where you find yourself stuck in situations like:
def foo():
try:
return d1[k1] + d2[k2]
except KeyError as e:
""" now what? which lookup failed? """
and have to resort to clumsy workarounds.> Amazing to me that the same people will laud Result because it lifts errors into signatures in Rust but hate checked exceptions because they lift errors into signatures in Java.
I don’t think you can write a generic over a checked exception list in Java, which means higher-order functions cannot deal with them. Modern implementations just don’t bother. Meanwhile, when errors are values, improvements to the type system in the happy path will apply to the error path as well, because they don’t use distinct language facilities that have to be separately considered and specified.
Your explanation of what bothers you with results seems to be focused on one specific way of handling the result, and not very clear on what the issue is exactly.
> what's the difference between your program and one with exceptions
Sometimes, in a language where performance matters, you want an error to be handled as an exception, there's nothing wrong with having that option.
In other languages (e.g. Elm), using the same Result pattern would not give you that option, and force you to resolve the failure without ending the program, because the language's design goals are different (i.e. avoiding in-browser app crash is more important than performance).
> syntactically noisy
Yeah setting up semantics to make users aware of the potential failure and giving them options to solve them requires some syntax.
In the context of a discussion about golang, which also requires a specific pattern of code to explicitly handle failures, I'm not sure what's your point here.
> full of footguns
I fail to see where there's a footgun here? Result forces you to acknowledge errors, which Go doesn't. That's the opposite of a footgun.
The Try operator (`?`) is just a syntax sugar for return. You are free to ignore it. Just write the nested return. People like it for succinctness.
Yeet? I don't understand, do you mean the unstable operator? Rust doesn't have errors either.
> what's the difference between your program and one with exceptions except the Result program being syntactically noisy and full of footguns?
Exceptions keep the stacktrace, and have to be caught. They behave similar to panics. If panics were heavy and could be caught.
Rust errors aren't caught, they must be dealt with in whatever method invokes them. Try operator by being noisy, tells you - "Hey, you're potentially returning here". That's a feature. Having many return in method can both be a smell, or it could be fine. I can find what lines potentially return (by searching for `?`).
An exception can be mostly ignored, until it bubbles up god knows where. THAT IS A HUGE FOOTGUN. In Java/C# every line in your program becomes a quiet return. You can't find what line returns because EVERY LINE CAN.
How I hate it, that every second function call can break my program when it's clearly not a "halt the world, it's totally unrecoverable that the user sent us nonsense" type.
Return a Result and get on with your life!
https://github.com/rust-lang/rust-clippy/issues/8184#issuecomment-1003651774
error: indexing may panic
--> src/main.rs:100:57
|
100 | rtmp::header::BasicHeader::ID0 => u32::from(buffer[1]) + 64,
| ^^^^^^^^^
|
= help: consider using `.get(n)` or `.get_mut(n)` instead
= help: for further information visit https://rust-lang.github.io/rust-clippy/master/index.html#indexing_slicingI love Rust the language, but the current bazar of little bits of functionality scattered around in the form of a zoo of crates is such a mess compared to, say, Java's class library (I/O, data structures, std. algorthms for searching, sorting etc., arranged in a logically and hierarchially named way).
I'm not against alternative implementations, but I'd rather have one "official" implementation that everyone knows that covers most cases and makes for the idiomatic reading of source code.
I mean, yes, but not an official one.
The stdlib is where good ideas go to die.
Waiting for "pub struct RDBMSInferfaceV17ThisTimeWeGotItRightForSure"
Sylvain Kerkour described the problems Rust faces by having a limited standard library:
"The time has come for Rust to graduate from a shadow employment program in Big Tech companies to a programming language empowering the masses of engineers (and not just "programmers") wanting to build efficient and robust sfotware.
What crypto library should we use? ring, RustCrypto, rust-crypto (don't use it!), boring, aws-lc-s or openssl?
Which HTTP framework? actix-web, axum, dropshot or hyper?
What about a time library? time, chrono or jiff (how I'm even supposed to find this one)?
You get it, if you are not constantly following the latest news, your code is already technical debt before it's even written. Fragmentation is exhausting.
I just looked at the dependencies of a medium-sized project I'm working on, and we have 5+ (!) different crpyto libraries: 2 different versions of ring, aws-lc-rs, boring, and various libraries from RustCrypto. All of this because our various dependencies have picked a different one for their own cryptographic usage. This is insane, first because it introduces a lot of supply chain attack entry points, but also because there is no way that we will audit all of them"
Source: https://kerkour.com/rust-stdx
My moderate-sized Rust web service project requires 587 third-party crates which seems ridiculous.
Fortunately, cargo makes it easy to manage the dependencies, but unfortunately I don't know how well supported or maintained the dependencies are. How well will they be maintained in five years from now? Will I need to find newer libraries and rewrite portions of my project to provide the same features that I have now? I don't know.
I’ve seen this argument, but if you look at real golang code and examples, it’s just a bunch of “if err <> nill” copy pasta on every line. It’s true that handling errors is painstaking, but nothing about golang makes that problem easier. It ends up being a manual, poor-man’s stack-trace with no real advantage over an automatically generated one like in Python.
Also, exception systems usually come with built in stack trace support, "this error caused by this other error" support, debugger integration ("break the first time something goes wrong"), and tons of other useful features.
(Common Lisp conditions are even better, but you can't have everything.)
You can't just wave the word "goto" around as if it were self-evident that nonlocal flow control is bad. It isn't.
> And nearly always, after an exception is “handled”, the application is actually in an unknown state and cannot be reasoned about.
That's not been my experience at all. Writing exception safe code is a matter of using your language's TWR/disposable/RAII/etc. facility. A programmer who can't get this right is going to bungle explicit error handling too.
Oh, and sum types? Have you read any real world Rust code? Junior developers just add unwrap() until things compile. The result is not only syntactic clutter, but also a program that just panics, which is throwing an exception, the first time something goes wrong.
Many junior developers struggle with error handling in general. They'll ignore error codes. They'll unwrap sum types. They might... well, they'll propagate exceptions non-fat ally, because that's the syntactic default, and that's usually the right thing. We have to design languages with misuse in mind.
If you really don't like unwrap[1], you can enable a linter warning that will let you know about its uses to flag it during code review. You know exactly where they are and when they happen. Exceptions are hidden control flow, so you rely on documentation to know when a function throws.
> Writing exception safe code is a matter of using your language's TWR/disposable/RAII/etc. facility. A programmer who can't get this right is going to bungle explicit error handling too.
Rust has RAII, so you don't have to worry about clean-up when returning errors. This is a Go problem, not Rust.
At the same time Checked Exceptions were a nightmare as well, because suddenly they were part of the contract, even though maybe wrong later.
And what would you do in that case? Since this is a future change your existing code presumably wouldn't know what else to do but throw its own exception, so why not just let that one propagate?
But then over in Java world, your checked exception paradise (which it of course isn't because the syntax and toolkit for managing the things is so clunky) is easily broken by the number of unchecked exceptions which could be thrown from anything at any time and break your code in unexpected and exciting ways, so not only do you have to deal with that system you also don't get any assurance that it's even worth doing.
But this doesn't actually mean checked exceptions are a bad idea, it means that Java didn't implement them very well (largely because it also has unchecked exceptions, and NullPointerException is unchecked because otherwise the burden of handling it would be hideous, but that comes down to reference types being nullable by default, which is a whole other barrel of pain they didn't have to do, and oh look, Go did the same thing wooo).
Depends on the area you look at. Language documentation is pretty good and so is documentation for the standard library itself. Documentation for the frameworks can be hit or miss. EF Core is pretty well documented and it’s easy to find what to look for usually. GUI frameworks are more of a learning curve however.
FWIW many in Java community consider checked exceptions to be a mistake. While I don’t find writing code that has many failure modes particularly fun with exception handling - Rust perfected the solution to this (and the Go way is visually abrasive, no thanks), I don’t think it’s particularly egregious either - Try pattern is pretty popular and idiomatic to use or implement, and business code often uses its own Result abstractions - switch expressions are pretty good at handling these. Personally, I’d write such code in F# instead which is a recent discovery I can’t believe so few know how good it is.
1. Exceptions are expensive (at least in Java / C#), as they generate a stack trace every time. Which is fine for actually exceptional situations, the equivalent of `panic()` in Go, but:
2. Exceptions are thrown for situations that are not exceptional, e.g. files that don't exist, database rows that don't exist, etc. Those are simple business logic cases. The workaround is defensive coding, check if the file exists first, check if the row exists? that kind of thing.
3. The inconsistency between checked and unchecked exceptions.
4. Distance - but this is developer / implementation specific - between calling a function that can throw an error and handling it.
But #2 is the big one I think. Go's error handling is one solution, but if it's about correct code, then more functional languages that use the Either pattern or whatever it's called formally are even better. Go's approach is the more / most pragmatic of the options.
Ugh NO. Please don't. You should never "check if the file exists first". It can stop existing between your check and your later attempt at opening the file (the same with database rows). That can even lead to security issues. The name for that kind of programming mistake, as a vulnerability class, is TOCTOU (time-of-check to time-of-use).
The correct way is always to try to do the operation in a single step, and handle the "does not exist" error return, be it a traditional error return (negative result with errno as ENOENT), a sum type (either the result or an error), or an exception.
an exception is meant for EXCEPTIONAL behavior.
So it may be that the file access throws an exception but generally, I wouldn't agree.
Sure, you can only do it way up the stack, but that's not enough quite often.
If you can only do it all the way up, I find it ergonomic.
Maybe I should experiment more with catch unwind in Rust.
Junior developers will write suboptimal code in any language. So I'm not sure what your point is.
I shocked my Professor at university with that statement. After I started laughing, he asked me more questions... still went away with a straight A ;D
To me this proved that there's nothing inherently wrong about exceptions.
It's how you structure your code and the implied assumptions you share with your colleagues.
Some people are way too optimistic about their program will actually do.
Happy path programming.
Or how does one optionally throw and exception without an "if" statement? What's the "base" exception call?
Ie if "if" is implemented via exceptions, how do exceptions get triggered?
And is "while" done via an "if exception" and recursion? Or another way?
https://blog.plan99.net/what-s-wrong-with-exceptions-nothing...
> Even junior engineers have a trivial time debugging most go errors
Not my experience at all. I had to do this once. An HTTP request to a production server was yielding a 400 Bad Request with no useful information for what was bad about it. No problem, I'll check the logs and look at the source code. Useless: the server was written in Go and the logs had no information about where the error was originating. It was just getting propagated up via return codes and not logged properly. It ended up being faster to blackbox reverse engineer the server. In a language with exceptions there'd have been a stack trace that pinpointed exactly where the error originated, the story of how it was handled, and the story of how the program got there.
Diagnosing errors given stack traces is very easy. I've regularly diagnosed subtle bugs given just logs+stack trace and nothing else. I've also had to do the same for platforms that only have error codes that aren't Go (like Windows). It's much, much harder.
This is the most important aspect of exceptions in my view.
The line that threw the exception isn't even the part of a stack trace that I find most interesting. The part that is most valuable to me when working on complex production systems are all of the call sites leading up to that point.
I remember in my junior years I wasn't a big fan of exceptions. A stack trace would make my eyes glaze over. I would try/catch at really deep levels of abstraction and try to suppress errors too early. It took me a solid ~5 years before I was like "yes, exceptions are good and here's why". I think a lot of this boils down to experience and suffering the consequences of bad design enough times.
Still, better to have too much data than too little.
In your map example, just add a scope guard that removes the just-added element using the returned iterator if the rest of the procedure doesn't succeed. It's no different in Java.
That sort of thing can help yes. But it's still way harder to get exception safety right in a language with manual memory management. In a GCd language you only have to be careful about cleaning up non-GCd resources, whereas in C++ you have to be ready for the expected lifetimes of things to be violated by exception unwinds at many different points and if you get it wrong, you corrupt the heap. Very few C++ codebases use exceptions vs all of them for Java, and I think that's why.
Go has support for exceptions, not to mention providing runtime access to stack trace information in general. They are most definitely there if your application requirements necessitate, which it seems yours did. Unfortunately, language support only helps if your developers actually speak the language. Go in particular seems especially prone to attracting developers who are familiar with other languages, who insist on continuing to try to write code in those other languages without consideration for how this one might be different and then blame the technology when things don't work out...
Not true at all
* goto goes to a specific hard-coded address
* return looks up the previous address from the stack and goes there
* exceptions are a complex mess that require branching logic to determine where to resume execution
On the flip side I have yet to find a person who’s familiar with sum types (e.g., Maybe, Option, Result) that finds the golang approach even remotely acceptable.
I've been working on one [1].
But gosh, does go make it hard.
While I much prefer Python as a language, Go wins against Python by having a fresher ecosystem, with a higher baseline for type safety. Still pretty low with respect to Rust or mypy/pyright with highest settings, but much better than any of the Python frameworks I've had to deal with.
It's a Google solution to Google scale problems, e.g. codebases with millions of lines of code worked on by thousands of developers. Problems that few people that have an Opinion on Go will ever encounter.
I don't LIKE it, but it's acceptable.
I have been working with Rust since 2015 (albeit not professionally, but a lot of side projects) and love it.
But I also dabbled into go the last couple of months and while it has its warts, I see it as another tool in the tool-belt with different trade-offs.
Error handling is weird, but it's working, so shrug
As I pointed out I think Rust does it better with its types error handling. That isn’t too relevant for me though as Rust will probably never seem any form of adoption in my part of the world. I think Zig may have a better chance considering how interoperable it is with C, but around here the C++ folks are simply sticking with C++.
I disagree. Typescript, C# and Java are terrible languages (as are Python/Ruby/etc. in other ways). Golang is bad by OP's standards but there's nothing wrong with it gaining ground on those languages.
Besides it's also easier to convert a codebase to Rust from Golang than Typescript or C#/Java.
I’d frankly pick Python for most things though. It’s a terrible language, everyone knows it’s terrible but it gets things done and everyone can work with it. I view performance issues a little different than most people though. To me hitting the wall where you can no longer “make do” with C/Zig replacements of Python bottlenecks means you’ve made it. The vast majority of software projects will never be successful enough to get there.
However, I do agree that it could be argued that Golang has become much more of a Java and C# alternative. Looks like Rust will be shoehorned into C++ and C spaces, but it remains to be seen how successful it will be as an C alternative. Seems like many fans of C are quite resistant or even outright dislike Rust.
Positive example of good and appropriate usage here: https://github.com/coder/websocket/blob/master/internal/exam...
So... I'd say that this is a fumble in the design of Go.
For example, the lib produces some an error "bad file descriptor". You'll be wrapping it when you call fileOpen, fileDelete, etc etc 20 times. So you will be wrapping it in "open error", "delete error", etc, 20 times. You cannot try to match it to "bad file descriptor", that information is lost, you now have 20 relatively useless errors.
Except if you stringly match.
It's better than nothing, of course.
Go, however, forces you to spread your error handling over a thousand little pieces with zero overview or control of what's happening.
Rust eventually realised this and introduced try! and ? to simplify this
A problem I often face in Go and TypeScript code is code that ignores errors, often unintentionally. For instance, many uses of JSON.parse in TypeScript do not check for the SyntaxError that may be thrown. In Go, it is common to see patterns like
_ := foo.Bar()
// assume Bar() returns error
This pattern exists to tell the reader "I don't care if this method returns an error". It allows one to avoid returning an error, but it also stops the caller from ever being handle to the error.Also, the position of the error matters. While the convention in the stdlib is to return errors as the final value, this isn't necessarily followed by third party code.
Similarly, errors are just an interface and there is no requirement to actually handle returned errors. Even if one wants to handle errors, it's quite awkward having to use errors.As or errors.Is to look into a (possibly wrapped) chain of errors.
The benefit of Rust's Result<T, E> is that
- position doesn't matter
- there is strong, static type checking
- the language provides operators like ? to effortlessly pass errors up the call stack, and
- the language provides pattern matching, so it's easy to exhaustively handle errors in a Result
The last two points are extremely important. It's what prevents boilerplate like
if err != nil {
return nil, err
}
and it's what allows one to write type-safe code rather than guess whether errors.As() or errors.Is() should be used to handle a returned error.It is unfortunate that many of Typescript developers still rely on throwing exceptions around (even in their own typescript code). Result types are totally doable in Typescript and you can always wrap native calls to return result types.
90% of the criticism of exceptions I see comes from the bizarre and mistaken idea that every call needs to be wrapped in a try block and every possible error mentioned.
Is there in practice a significant difference between try/catch and Go's "if err" ? Both seem to achieve the same purpose, though try/catch can cover a whole bunch of logic rather than a single function. Is that the only difference ?
I think that's the biggest difference.
With Go you need to specifically check the errors and intentionally decide what to do, do you handle it right there or do you bubble it upwards. If you do, what kind of context would the caller want from this piece of code, you can add that too.
Compared to Go, this is actually better because the type system can tell you what kind of errors to expect, instead of just "error".
Is this really all that interesting or worth the LOC spent on error handling when 99.9999% of the time in practice it’s just bubbled up?
And any “context” added is just string wrapping. Approximately nobody types golang errors in a way that lets you programmatically know what went wrong, to be able to fix it in-line.
I think I would be more empathetic to the arguments defending golang here if I’d ever worked or seen a project where people actually handled errors instead of spending 2/3 of their time writing code that just punts on any error.
That was prototyped around Rust 0.4, so I wouldn't say "eventually" :)
Like as soon as I wanted to try and get sensible reporting in their, suddenly we were relieving libraries, adding shims and fighting mismatched types and every article was saying the same thing: haha yeah it's kind of a problem.
I'm very, very unsold on explicit error handling compared to exceptions for practical programming. The number of things which can error in a program is far larger then those that can't.
Even the simplest functions tend to have error states - i.e. floating point math can always wind up handing back NaN.
So where I end up is, the default assumption is every function is effectively of a type MightError(T)...so why even make us type this? Why not just assume it, assume the unwrap handling code, and so you basically wind up back at try-catch exception handling as a syntactic sugar for that whole system.
I kind of see your point. In this very moment, it doesn't matter whether I agree. What I don't understand, though, is why (typically) people who abhor exceptions are among the fiercest defenders of garbage collection, which does add a “magic” and uncontrollable layer to object destruction.
Personally, having learned to love RAII with C++, I was shocked to discover that other languages discarded it initially and had to add it in later when they realized that their target developers are not as dummy as those choosing Golang.
on this point go's error handling is a massive fail. Notice that I'm not saying explicit error handling is bad. I'm saying the insistence that error handling needs to be implemented inline interleaved with the happy path is the problem. You can have explicit error handling in dedicated error handling sections
Some people didn't like the "try" keyword it reminded them too much of exceptions, some people didn't like that they couldnt see a return inline (which was the purpose of the proposal in the first place).
it's not that there are no solutions. the main problem is the go team's insistence to have "one true way" (tm) of doing something and unfortunately this gap between people who want to see every return inline and people who want to see the clean solution separate from the error handling is not something that can be bridged by technical means. the only solution is to implement both ways and lets see which one wins.
It's basically the same syntactic sugar as `try!` in Rust, isn't it?
maybe this has something to do with how bug-prone it usually is for a new hire to modify a codebase for the first time in most orgs
you could also just do things fail-fast style and panic everywhere if you REALLY wanted to stop inlining error conditions. or ignore error checks until some sort of guard layer that validates things.
IME you usually don't want to do either of those things, and the go approach at least encourages you to think about it closer to the site than checked exceptions (which you can more easily toss up and up and up and auto-add to signatures of callers). unchecked exceptions are arguably less-bad than "just ignore go return errors" - they'll get seen! - but terrible for a reliability/UX perspective.
optional-esque approaches are nice but just a different flavor of the same overhead IMO.
Honestly makes me wonder what I'm missing. Maybe it's because I don't deal with state much? Do the problems start to mount up when you get into writing transaction locks, rollbacks etc? But I don't see why you wouldn't have the same problems with Go's mechanism.
Hoping to gain enlightenment here.
[copied from a comment below]: They are just horrific gotos that any library can invoke against your code. They are pretty much never, ever handled correctly. And nearly always, after an exception is “handled”, the application is actually in an unknown state and cannot be reasoned about.
Maybe this is it? I prefer a "fail early and often" approach, and I tend to validate my data before I perform operations on it. I don't want to attempt recovery, I want to spew log messages and quit.
I think that’s misdirected but illustrates the emotional reasons why people develop a negative impression of the concept. Usually it means someone had bad experiences with code written in a poor culture of error handling (e.g. certain Java frameworks) and generalized it to “exceptions are bad” rather than recognizing that error handling isn’t trivial and many programmers don’t take it seriously enough, regardless of the paradigm. As a simple example, C and PHP code have had many, many security and correctness issues caused by _not_ having errors interrupt program execution where the users would have been much better off had the program simply halted on the first unhandled error.
If you write complex programs with lots of mutable shared state, yes, it’s hard to reason about error recovery but that’s misattributing the problem to the mechanism which surfaced the error rather than the fact that their program’s architecture makes it hard to rollback or recover.
The big issue with exceptions in C#, Python and JS is that they're not included in function signatures, which means you have to look up the list of possible exceptions from documentation or source code. This could be amended with checked exceptions like Java, but it allegedly doesn't mesh well with the type system (I haven't personally written Java to confirm this). And then there's the C++ crowd that slaps noexcept on everything for possible performance gains.
Personally, I like the way Koka does exceptions with algebraic effects and type inference. It makes exceptions explicit in function signatures but I don't have to rewrite all the return types (like in Rust) because type inference takes care of all that. It also meshes beautifully with the type system, and the same effect system also generalizes to async, generators, forking and other stuff. Alas, Koka is but a research language, so I still write C# for a living.
Yes - for me, the simplicity is essential. As a part-time programmer, I don't have months to spend learning C++ or Rust.
If my project needs to compile to small(-ish) standalone binaries for multiple platforms (ruling out Python, Ruby, Java, C#, etc) what simple alternative language is there? Plain C?
Staying in that lane. In my part of the world Go is seeing adoption that no other “new” language has exactly because of its simplicity. It’s not the best language, but it’s often the best general purpose language because it has a lot of build in opinions which protect you from yourself.