Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

Because the alternative is worse. If you test-and-return after every call, your function has multiple exit points and is far less maintainable. If you nest like this, you at least have a chance of maintaining a single exit point in your function (even though this example fails to do so).

This is why the Lord invented exceptions, which it seems that Go does not use. This one example is enough to convince me to never use Go for anything. What a huge step backwards.



I encounter this argument daily and I believe it usually comes from programming dogma of people who read very assertive quotes from Dijkstra.

Most of the time when error checking, returns (or in C, gotos) are fine and lead to more readable code that's easy to make sense of and easy to step through with a debugger.

    Please don't fall into the trap of believing that I am 
    terribly dogmatic about [the go to statement]. I have the 
    uncomfortable feeling that others are making a religion 
    out of it, as if the conceptual problems of programming 
    could be solved by a simple trick, by a simple form of 
    coding discipline!
- Dijkstra (1973) in personal communication to Donald Knuth , quoted in Knuth's "Structured Programming with go to Statements"

https://en.wikiquote.org/wiki/Edsger_W._Dijkstra


> your function has multiple exit points

That's a good thing.

> and is far less maintainable

I'd say it's more maintainable.

> you at least have a chance of maintaining a single exit point in your function

Maintaining a single exit point is IMHO an anti-pattern; it makes ugly unmaintainable deeply nested code.


> If you test-and-return after every call, your function has multiple exit points and is far less maintainable.

There is nothing wrong with multiple exit points as long as:

a. the language has a mechanism for scoped resource allocation (ie. defer, finally, with, unwind-protect or "RAII")

b. the early exit doesn't happen in the middle of a long and complex function


> a. the language has a mechanism for scoped resource allocation (ie. defer, finally, with, unwind-protect or "RAII")

Just being pedantic here. RAII is more specific than the defer statement that Go offers. Strictly speaking, defer is not RAII.


I always use a single exit point in my functions and also a goto to get there from the middle.




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: