This is a response for Go 2 error handling proposal.
Proposed in drafts check/handle
error handling method adds more complexity, than comfort for developers and make application less maintainable.
The most annoying problem of the current error handling way in Go is the construct if err != nil {
, this check is the most popular and developers should repeat it again and again.
So we propose to optimize exactly this pattern, only error handling condition part by reusing !
operator, which could be used as a prefix in conditions, and will be used to check if a variable is not equal to nil
.
Here's an example:
Instead of:
a, err = somefunc()
if err != nil {
// do something
}
Use:
a, err = somefunc()
if !err {
// do something
}
Conditional logic pattern return err
, is not so popular, as draft's authors suppose. So we propose not to optimize it.
Here's an example of statistics on real projects, which proves it.
$ find go/src/github.com/ -type f|xargs pcregrep -Ms --buffer-size 1048576 'if err \!= nil {\n.*(\t)'|wc
206408 1133371 17978161
$ find go/src/github.com/ -type f|xargs pcregrep -Ms --buffer-size 1048576 'if err \!= nil {\n.*(\t)return err'|wc
13422 55138 801746
Only around 5% of conditions in real projects directly returns errors. You could make such check on Your own project libraries to check it.
The proposed method of error handling has the following advantages over the existing proposal draft:
- It doesn't require any new keywords.
- It uses classic Go error handling, and simply optimizes the syntax, it's easy to adopt.
- It keeps the logic concentrated, so the developer don't need to jump through files to find the good handler.
- Developers could use traditional error handling with
if err {condition}
for own logic as usual.
The draft design documents do say they analyzed a large codebase for
return err
vs other handling code and found that return was the most common. However that's not the case in my projects, so I tend to agree with you.