How to Error Handle in Go [on hold]


I am new to Go. What I noticed was that most online resources handle errors using if err != nil. However, there are some cases where doing the reverse would actually reduce nesting ie. if err == nil { return something, nil }



for instance something like the following



however, couldn't this be simplified to the following:



Is it incorrect to do this? If not, what would be the reasons against it?



Many good questions generate some degree of opinion based on expert experience, but answers to this question will tend to be almost entirely based on opinions, rather than facts, references, or specific expertise. If this question can be reworded to fit the rules in the help center, please edit the question.



Both snippets produce identical results, and there's not necessarily a "right" or "wrong" here.



It is, however, strongly advisable to pick one style and stick with it. Consistency is key.



Most Go code I've seen strives to use indented blocks for error handling - typically through early exits. The happy path is generally not indented or inside (nested) control structures.



So - most developers would expect this:



instead of:



This is very convenient: when reading code, it feels like you're reading a story. You get used to the fact that indented code is typically an alternative flow/path.



Finally - when there's 9 occurrences of err != nil, it's fair to assume the odds of you distinguishing the err == nil on the tenth occurrence are pretty slim.



A very related blog post that describes this problem can be found here.



In special cases, when the check is the last thing in a function, this might be OK, but I am generally against doing this, because:

Popular posts from this blog

The Dalles, Oregon

“Thánh nhọ” Lee Kwang Soo chúc thi tốt, sĩ tử Việt Nam... có dám nhận hay không?

眉山市