4 ms·
Sure it is important but I have had functions looked like this func foo() error { a, err := bar() if err != nil { return err }
by qtplatypus 7y ago
Sure it is important but I have had functions looked like this
func foo() error {
a, err := bar()
if err != nil {
return err
}
b, err := baz(a)
if err != nil {
return err
}
...
}
In some code this error handeling is 3/4 of the function lines. Sure the error behavior is important but is it 3 times more important then the logic of what you are writing?
The if nill construct contributes to cognitive load and detracts from code plainly tells you what it does. And speaking from a practical perspective I’m going to be far more productive if 3 lines of commonly used code is turned into five characters.
- marcus_holmes 7y agoYes, that's how Go code looks, it has a rhythm of "do something, check for errors, do something, check for errors". This is a great idea, because checking for errors is explicit, and dealing with them is immediate. After a while of working in Go, you get used to the rhythm and you stop noticing the "check for errors" part unless it does something different. You also notice when the check is missing. And having most of your code devoted to error handling makes total sense. There are usually lots of errors states and only one "golden path" state - properly handling all the possible errors your code could generate will mean writing more error-handling code than logic code because there are more error states than non-error states it can get into.
- qtplatypus 7y agoAll “try” does is allow you to write those three lines as five characters. In natural languages the more frequent used a word is the shorter that word tends to be. “Check for errors and return” is something that is frequently said in go, following from those principles it should be something that it short to write.
- marcus_holmes 7y agoI see that, but it breaks the rhythm, and introduces an alternative syntax that makes it harder, not easier, to read. And code should be easier to read than to write, because we're going to read it way more than we write it. Instead of "do something, check for errors, do something, check for errors" we would have "do something, check for errors, try something, do something, check for errors" (assuming not all errors are going to be "try"d, and some will need to be wrapped). It stops being obvious when I've missed an error-check. That's bad.
- qtplatypus 7y agoHow can you miss an error check? Either you have used try and therefor there has been a check for errors. Or you have not used try and therefor you had to assign to err and therefor you have to use a check for errors. Any assignment to err indicates you need to check for errors just like it is currently.