The ongoing Go survey asked a question about satisfaction with error
handling in Go.  I'd like to express an opinion on it that I haven't seen
elsewhere, for which there was not room in the survey.

I am generally a fan of the explicit error handling code in Go, but I get
frustrated by the interactions between error handling, := assignments, and
compiler warnings.  My preferred way of writing the standard clause is

if err := fn(); err != nil {

    // handle error and bail out
}


However, often the function in question returns a result I want to work
with.  If it's something important for the whole rest of the function, I'll
probably just define it as a variable at function scope:

var (

    result sometype

    err error
)
// ...

if result, err = fn(); err != nil {

    // handle error and bail out
}

// act on result


But often, the result is something I'm only going to use for one statement
and is not a variable of significance to the whole function.  Those are the
sorts of cases that := is best for, in my opinion.  In those cases, what
I'd like to write is

if result, err := fn(); err != nil {

    // handle error and bail out

} else {

    // act on result
}


Unfortunately, the compiler gives a warning on that.  Because the truth
clause bailed out (e.g., "return"), it insists that I remove the else and
turn the code into

if result, err := fn(); err != nil {

    // handle error and bail out

}

// act on result


But that doesn't compile because result is no longer in scope.

What I often wind up doing instead is

if result, err = fn(); err == nil {

    // act on result

} else {

    // handle error and bail out
}


That works, but it leaves my code with a mixture of "handle error case
first, then success" and "handle success case first, then error" patterns,
which I find adds a lot to cognitive load.

I have no idea whether others share my frustration on this admittedly minor
point.  But since the survey prodded me, I thought I would voice it and see
what reactions it gets.  For me, the ideal solution would be to suppress
the compiler warning about removing the else, when doing so would break the
code altogether.

Regards,
Steve

-- 
You received this message because you are subscribed to the Google Groups 
"golang-nuts" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to golang-nuts+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/golang-nuts/CAAnpqKGFcuk%3DZtRSqQE5QOb%2BmHWmXxxaCDJE9PY9BzUsv5DdJQ%40mail.gmail.com.

Reply via email to