Idiomatic Go Question
from tapdattl@lemmy.world to golang@programming.dev on 23 Apr 01:10
https://lemmy.world/post/45955160
from tapdattl@lemmy.world to golang@programming.dev on 23 Apr 01:10
https://lemmy.world/post/45955160
Given the following short function
func example(foo string) error {
if bar, err := doSomething(foo); err != nil {
return err
} else {
doSomethingElse(bar)
}
return nil
}
Why does the linter recommend I change the if block to
var bar whateverType
if bar, err = doSomething(foo); err != nil {
return err
}
doSomethingElse(bar)
return nil
}
In my mind the former example restricts the bar variable to the smallest scope that is needed, and more clearly identifies doSomethingElse as something that should only happen if err != nil.
I know it’s redundant, but now if I want to change it to an else if … chain I don’t have to worry about accidentally including or excluding code from that block, I already know exactly what’s supposed to be in it. I just feel like it’s a safer programming practice.
But looking forward to other opinions and discussion. Thanks!
#golang
threaded - newest
Coming from C (with MISRA and flexelint) I also thought this idiom was a bit ‘ick’ in Go… but I guess they feel a return in an if-block makes the else redundant.
I was taught (again, in C/C++) that one should strive for single return points in functions, so actually either of these forms bug me to some extent.
In Go one can name the return variable(s) in the func declaration line, eg.
func example(foo string) (e error) { /* e is implicitly nil so far */ if bar, e := doSomething(foo); e != nil { /* e was set above to non-nil */ } else { doSomethingElse(bar) } return e /* or just 'return' */ }…but that’s not ‘idiomatic’ Go either :)
I can’t speak for Go’s maintainers, but your story fits a pattern I’ve noticed: The language, standard library, and toolchain are excessively prescriptive about how things should be done, while insufficiently considerate of diversity in people’s needs. Ergonomics suffer because of it, as do other things that I find important.
Nit: I think you meant to write, “should only happen if err == nil.”
@RemindMe@programming.dev 36 hours
IMO that’s less idiomatic Go, more just plain old clearly written code. Whenever possible, the nominal (non-error) path should stay at the same level of indentation. Indentation should be reserved (as much as is possible) for loops and atypical conditions (including errors).