Hacker News new | ask | show | jobs
by jzelinskie 4361 days ago
I could get behind the Go compiler to forcing people to write "_ = errReturningFunc()" instead of simply "errReturningFunc()" if they want to explicitly ignore errors.

In my recent experience, it actually bothers me a lot that funcs in the standard library would often rather return nil or the zero-value of a type than change the signature of the func to return (T, err). I don't really care that the docs describe that behavior -- that behavior is an error.

2 comments

The thing is, compilers can force people to refer to error variables, but they can't prevent people from returning array[0] when i is out of array[]'s bounds, an empty list given an empty JSON string, etc. And forcing the former unfortunately only encourages the latter.
Returning (T, err) means that the function cannot be used as part of a larger expression. That's the main issue with this idiom in my view.
This is a feature. The statement might not succeed. You shouldn't use it as part of a bigger expression and assume it will work.

    t, err := foo()
    if err != nil {
        return err
    }
    bar(t)
this makes it totally clear that foo can fail, and if it does, then we won't call bar.

In languages with exceptions, this line just looks like

    bar(foo())
And then you can't tell that foo might fail and we might not call bar. Even if you wrap the whole thing in a try/catch, it's not clear.

This is why exceptions are an anti-pattern. They hide what functions can fail and what happens when they do.