One of the things Go taught me is that I was not being as careful about my errors as I should be. It can be argued that exception-based handling provides you a nice baseline default, but it makes it way to easy when doing network or system-type programming to thoughtlessly default to that, when you need to be thoughtfully defaulting to that.
With sufficient care, exception-based programming and errors-as-values converge in the end anyhow in "code that treats errors correctly". But my exception-based code is a lot more informed by the errors-as-values approach now; a lot more try statements with catch statements that actually do something.
Even Haskell's very nice Either monadic handling can make it too easy to be in the heat of the moment and not thinking about what the errors actually mean and what I can do about them.
I don't think it's appropriate for every domain, which is why I qualified the code I tend to work on. But in those domains I'm thinking a lot more about how every single line of code can go wrong rather than leaning on default exception-based handling and expecting it all to work out.
I identify with this so much. Especially when dealing with external things (file system, database, network) things can go wrong at nearly every step. And yeah, that means you have to check errors at every step, but it forces you to think about how you want to handle them, and what message you want to propagate when they happen. As a result, my Go code has very few unexpected errors in production.
Handling errors everywhere means problems are already solved before they happen. No 1 am pagerduty alerts because we didn't consider what would happen if a DNS server hung until we timed out and thought just wrapping in a try/catch and crashing was a good idea.
To get into a situation where you'd need to handle n! cases, you'd need to keep running the statements after a failure, and then collate and return all the errors at the end.
Not sure why you'd want to do that. You'd definitely need to go out of your way to do something like this, and probably start asking yourself why you're doing this pretty early on. Plus it would flat out refuse to compile in some cases where there are dependencies between the statements.
{n + 1 \choose n - 1}
What code are you writing that results in this set of possibilities?There is no hard technical line between "unit test" and "integration tests", it's a semantic question of how you define your units. Even if do you take a tiny, restrictive definition of your units, you could still use a fake or stub instead of a mock.
https://martinfowler.com/articles/mocksArentStubs.html
To get very specific for Go, we use testify suites, tend to set up fully functional stubs in `SetUp`, and then test cases either use them to verify happy paths, or `s.BreakStep1()` in one test, `s.BreakStep2()` in the next, etc. So in this case we would write a total of five extra lines for the five possible ways to break.
let _ = openFile()
Error ignored, it does compile, it will probably ends badly.
As for network error: https://pkg.go.dev/net#OpError
The whole point of a programming language is to make the programmers life easier.
By now decades of exposure to programming languages have made try/catch the standard way of working with errors. Forcing the programmer to guess issues, when the compiler/runtime could be doing it- IMO is just plain waste of human labor. And for even medium to large applications is a pointless exercise.
a, err := foo() // oops, unhandled error
err = bar()
if err != nil { ... }
or fmt.Println("...") // oops, unhandled error
or more insidiously err1 := foo()
if err1 != nil { ... }
err2 := bar()
if err2 != nil { return err1 } // oopsThey do, they throw exceptions.
> In the first and the last case, it seems obvious to me where the error is
The last case is especially insidious. I've seen it in production several times now. Very easy to miss. Particularly when refactoring/copy pasting code (which you have to do a lot of in golang).
I see a lot of the same issues in Rust code today FWIW. People just keep bubbling up errors and at the toplevel say "fuck it" and dump them, without _actually_ building a reasonable error chain to offer the programmer a story behind how the error happened. The fact is, error handling in any language is tedious. Whether you do it with a sum type, a product type, or Go's error values, either way there's going to be lots of verbosity and boilerplate.
You can successfully build huge chains of code that are just blindly passing errors up without adding any context about where they happened or anything in a way that even Rust can't compete with.
Haskell mitigates this issue by also having one of the more clever ways of dealing with errors, if you start getting into monad transformers or some of the advanced stuff, so it's not all bad. But it definitely can make it so easy to "handle" errors that you just forget about them.
Go would benefit a lot more from some basic slice manipulation tools compared to features like generics that have actually made it into the language.
The error handling I don't find so frustrating - it's great that it explicitly marks at the call site which functions can potentially error. It's like a working version of an inverse noexcept from C++. I do wish they would take a leaf out of swifts book though, with the try keyword. In practice error handling flow in my go programs is identical to using exceptions, it would be nice to have some helpers to make this default less verbose without losing the ability to distinguish at the call site which calls are error-y.
if err != nil { return err }
if res, err := actually_important_bits(...); err != nil {
return nil, err
}
The actually important bits are hidden in the middle of line noise. In the "common case" where `actually_important_bits` is just a simple function call it's not necessarily as bad, but the problem is when you have ten successive instances of this and one is slightly different. It's impossible to notice the important difference at a glance.For an industry that is just starting to understand that code is read hundreds of times more often than it's written, golang fails at the few things we actually know for certain about what makes it easier to understand code at a glance.
res, err := actuallyImportantBits(...)
if err != nil {
return nil, fmt.Errorf("actually important bits: %w", err)
}
And other times you have to do this: if err := actuallyImportantBits(...); err != nil {
return nil, fmt.Errorf("actually important bits: %w", err)
}
The problem here is that you really don't want "err" to leak to the outer scope, so the second case is preferable from an absolute reliability and least-surprise perspective... but you can only do that in certain arbitrary cases. I think it's a bit of a wart.You can certainly handle "res" in an else block, or even write "err == nil" and handle it there, but that is surprsing. I would say it's simply not done, ever, but the Go codebase itself does it (src/go/parser/interface.go.ParseDir was the first example I found; but my search returned many screenfuls of candidates so there are probably more cases lurking in there).
The fact that you have a choice is not ideal, basically.
But, having actually important bits in if err := ...; err != nil {} blocks is not detrimental to readability. You will know how to read that after 5 minutes of reading any Go program.
res, err := ...
if err != nil {
return nil, fmt.Errorf("...: %w", err)
}
for that exact reason. This doesn't scan any worse than any other text-based code. (Page in the people selling visual programming here.)I'm far from a Go expert, but I feel like this line is a bit pointless, especially if you write it a lot. At this point, why not just not handle the error, or panic?
Let's say you've got a function that reads from a file. If the file doesn't exist, what do you do? That entirely depends on the context the function is called in. If it's in a web server, you might return a 404. If it's a background task polling for some data, you might sleep for a while until the file is uploaded. Or you might want to create the file yourself.
At high scale, you want to perhaps try your query a few more times, backing off exponentially, maybe even round-robining (or more complicated load balancing) among different targets. Throwing up your hands and 5xx-ing a request that easily is not something you can afford at high scales of traffic where small outages happen _all the time_.
so basically you mean that this only applies to like 0.001% of all websites/apps.
thus it's stupid to do it. I mean even than you would have an error that you need to bubble up or circuit break it somwhere but probably not at this layer.
also KISS and MVP, never ever overcomplicate something when you do not know anything yet, so most people don't need to built for scale at day 1 and it also is stupid to do it.
IMO if Go didn’t have its tooling, no one would care about it.
every if err != nil; return err let's me mentally draw a line in the sand and not worry about exception handling for code above that line. It lets me start fresh and restart my mental model with the line of codes below the error handling block.
it doesn't take years of writing Go to understand this, all you need is a open mind to how Go does things.
My code is almost exactly:
err := doThing()
if err != nil {
return err
}err = doAnotherThing()
if err != nil {
return err
}etc.
There's no need for me to "start fresh". Each line of actual stuff doing might return an error which needs to be returned. That's it. It's a complete waste of space and inhibits readability to absolutely no benefit. And this is extremely common across our code base.
Which is also the hardest part of convincing people to use Go for me: "Why can't I just .map()/.filter()/.find()?" followed closely by "Why do I always have to check for errors?"
What is odd to me is that while yes, my Go code is more verbose than my node services - I always end up writing less Go for the same thing.