3 ms·
The 'defer file.Close()' ignoring errors is used throughout the examples for golang so I assumed it was the same here. My bad. you insist on making the wrong
by 0xABADC0DA 14y ago
The 'defer file.Close()' ignoring errors is used throughout the examples for golang so I assumed it was the same here. My bad.
you insist on making the wrong choice up front, which is to use defer for something which is non-trivial.
Closing a file is non-trivial? So you have multiple returns in the function and you also need to close the file... better repeat it several times instead of using 'defer'. I'm not sure what the point of 'defer' is if that is the case.
Also the code you linked silently ignores the first N-1 errors, only returning the last one. Maybe in this case it is acceptable, but what kind of error does it return? Could the ignored errors be more relevant than the final one? Who knows.
- wonderzombie 14y agoI was just trying to argue in good faith by addressing the spirit of your criticism, not the letter of it. As I said, go and look at the prevailing usage of defer. Closing a file is trivial most of the time. When closing something (a file, net connection, db connection) you're really worried about, that's when you ought to think twice about using defer. That's really all I'm saying. I'm not sure what's wrong with multiple returns, as you're no worse off than if you were using exceptions. At least return is a standard, predictable mechanism which behaves the same regardless of what codebase you're in: exit the current function. You don't have to guess what file you need to look at next; control reverts to the caller. And, as far as the example code is concerned, it is completely orthogonal to exceptions vs. error codes. You still have to prioritize what's catastrophic enough to abort and notify the caller, and what isn't. The author decided those errors weren't important. So what's the big deal?