sqs / goreturns

A gofmt/goimports-like tool for Go programmers that fills in Go return statements with zero values to match the func return types
Other
530 stars 55 forks source link

Remove bare returns #24

Closed bancek closed 8 years ago

bancek commented 8 years ago

It converts

func Fb() (res int, err error) {
    err = errors.New("foo")
    return
}

into

func Fb() (res int, err error) {
    err = errors.New("foo")
    return res, err
}
sqs commented 8 years ago

Thanks! I will merge this. This is more disruptive Han plain goreturns because bare returns are often useful and beneficial for readability. I find I use them more as I have been coding Go for more years. But in the spirit of experiments and feature flags, let's give it a try.

How come you want to avoid bare returns? Or is it just you want goreturns to fill in the returns without you needing to even type anything after "return"?

bancek commented 8 years ago

I've been using bare returns for few years but I found it to be a source of many bugs and started using explicit returns.

Example:

func Fb() (res int, err error) {
    var result int

    result, err = Fc()
    if err != nil {
        return
    }

    return
}

If Fb was a really long function you could miss that you should store result into res. But if you used return res, err instead of just return it would be easier to spot that maybe you meant return result, err.

You also have more control of what you return. E.g. if Fc() returned a wrong result with error you could forgot to check the error.

For me the following is much easier to understand:

func Fb() (res int, err error) {
    var result int

    result, err = Fc()
    if err != nil {
        return 0, err
    }

    return result, nil
}
dmitshur commented 8 years ago

I agree very much with what @bancek said above. That has been my experience and preference too; I find it's much better to be more explicit about returns.