Open leighmcculloch opened 4 years ago
I think this is reasonable, though I don't plan to work on the shadow analyzer myself.
It's important to note that the shadow analyzer is experimental so its recommendations should not be considered best practices.
I'd be open to contributing a change to exclude error values. Would a contribution doing this be welcome?
I thought about this some more and I think we'd want to do something a bit more sophisticated: the example in Shadow's doc string uses err as an example of a shadowed variable... so I think it was intended for that variable to be flagged. I'm not sure exactly what a more sophisticated approach would look like...
What version of Go are you using (
go version
)?Does this issue reproduce with the latest release?
Yes
What operating system and processor architecture are you using (
go env
)?go env
OutputWhat did you do?
Fixed code according to the shadow analyzer, I renamed a variable from
err
to be distinguishable from another variable also namederr
that was in a higher scope.What did you expect to see?
I expected using unique names for variables in nested scopes to be a best practice since the shadow analyzer recommends it.
What did you see instead?
I'm experiencing that renaming
err
variables in code is more likely to create more human errors than to use shadowederr
variables.In Go code my colleagues and I have seen we have definitely found value in renaming shadowed variables, it's actually caught some bugs for us on a couple occassions, but when it comes to errors the opposite has been true. On one occasion the error lived on for a while in production code. Code had been written, a shadow was detected, a variable was renamed, the scope was removed and then this was the bug and fix when we discovered the bug that had been created by the attempt to not shadow: https://github.com/stellar/go/pull/2469. I've caught myself on another occasion making the same mistake. This might just be my weakness but I suspect others might make the same mistake as me.
This issue isn't about that specific issue but rather treating a shadowed
err
can easily create buggy code because developers may be accustomed to seeing the error namederr
, making it really easy to forget that in this one rare scope the error is nameddbErr
and to do things like return the error from the wrong scope.Proposal
Make
err
of typeerror
an exception to the shadow checker. The shadow checker already makes several exceptions on the basis of those patterns being common and idiomatic. This is another one of those patterns.cc @stamblerre