Sign in to follow this  
Structural

Early returns

Recommended Posts

Structural    328
What's so bad about them? I've read a few WTF's on www.thedailywtf.com, and I came across a few comments that were along the lines of "haha, an early return". I must admit I sometimes have the same habbit of doing early returns, especially while doing parameter validation early in the function or when an error occurs during processing. Why are they so bad? And what is the better alternative? Adding levels of indentation with extra if's doesn't seem to make code more comprehensible in my opinion, but I could be wrong there.

Share this post


Link to post
Share on other sites
Fruny    1658
In languages where you have to manually insert cleanup code, you have to make sure that cleanup is done on every path your function can return by. That's why some advocate that a function should have a unique exit point. That's also an argument some people use against exceptions.

In C++, destructors and the RAII idiom make that completely unnecessary.

I much, much prefer an early return ("ok, you don't have to deal with all that stuff, return now") or throwing an exception ("your parameters are bad, I can't do anything with them" or "I can't return a meaningful result") to a series of nested if statements.

Share this post


Link to post
Share on other sites
Rattenhirn    3114
Also, a bunch of exception throws or early return in the beginning of a method/function can't really harm clean up, since there's nothing to clean up yet.

However, early returns can be problematic when they are "hidden" somewhere in the middle of a method/function. They are quite easy to miss, if you have to maintain your old or foreign code.

So, in conclusion, I don't see problems with early return for parameter validation, but everything else should be avoided, if easily possible.

IMHO, of course. ;)

Share this post


Link to post
Share on other sites
Wyrframe    2426
The philosophy against early returns is just another throwback to the days of much simpler and more explicit programming languages, most of them simpler to the point that you can't really call them a language so much as syntactic sugar for machine code.

Not that syntactic sugar is bad. If it was a bad thing, we'd all be writing software with a hex editor.

Share this post


Link to post
Share on other sites
xor    516
Wow, i just realized how much of a problem this can be.

I am looking at a piece of code of a loading funtion, and this has files being opened, memory being allocated, etc. And to make an early return i just realized i have to clean everything i did before if something goes wrong. That includes closing all the files, freeing all the memory and nulling all the pointers used in memory allocation to avoid double frees and reseting a bunch of variables, for every early return i have.

This turned out to be a mess!

Share this post


Link to post
Share on other sites
snk_kid    1312
Quote:
Original post by xor
I am looking at a piece of code of a loading funtion, and this has files being opened, memory being allocated, etc. And to make an early return i just realized i have to clean everything i did before if something goes wrong. That includes closing all the files, freeing all the memory and nulling all the pointers used in memory allocation to avoid double frees and reseting a bunch of variables, for every early return i have.


If your using C++ you wouldn't have so much a problem if you used the standard library:

1. std::auto_ptr for RAII.
2. std::vector over C-style dynamic arrays.
3. std::basic_string over C-style dynamic strings.
4. C++ I/O file streams automatically closed when destructed.
5. using reference counted smart pointers.
6. pass by reference using (constant) references instead of plain pointers.

Share this post


Link to post
Share on other sites
Structural    328
Quote:
Original post by xor
Wow, i just realized how much of a problem this can be.

I am looking at a piece of code of a loading funtion, and this has files being opened, memory being allocated, etc. And to make an early return i just realized i have to clean everything i did before if something goes wrong. That includes closing all the files, freeing all the memory and nulling all the pointers used in memory allocation to avoid double frees and reseting a bunch of variables, for every early return i have.

This turned out to be a mess!


This is indeed a problem I recognise with using early returns, and at places like that I try to avoid them. I now have some duplicate cleanup code in some loaders because of this.
I also have the habbit of avoiding goto's like the plague, but sometimes I feel a "goto cleanup;" would really simplify some stuff.

Share this post


Link to post
Share on other sites
snk_kid    1312
Quote:
Original post by Structural
but sometimes I feel a "goto cleanup;" would really simplify some stuff.


Not really, using what i suggested in my previous post would, take advantage of destructors.

Share this post


Link to post
Share on other sites
Rattenhirn    3114
Quote:
Original post by Structural
This is indeed a problem I recognise with using early returns, and at places like that I try to avoid them. I now have some duplicate cleanup code in some loaders because of this.
I also have the habbit of avoiding goto's like the plague, but sometimes I feel a "goto cleanup;" would really simplify some stuff.


Interestingly enough, using some languages (like C# and Java for instance) you can have something like a "goto cleanup;" if you use the
try
{
// do stuff
}
finally
{
// cleanup
}
construct.

Share this post


Link to post
Share on other sites
antareus    576
Quote:
Original post by Rattenhirn
Interestingly enough, using some languages (like C# and Java for instance) you can have something like a "goto cleanup;" if you use the
try
{
// do stuff
}
finally
{
// cleanup
}
construct.

Prefer the using keyword to try/finally blocks in C# whenever the object being cleaned up implements IDisposable. The generated code is the same, but the using construct is considered idiomatic.

Share this post


Link to post
Share on other sites
Adding to what snk_kid said about using auto_ptr std::vector etc for RAII.

here's a nice way to enusre cleanup to:

void foo()
{
struct janitor
{
~janitor(void)
{
//put all neccessary cleanup code here
}
}clean_on_return;
//.. code including early returns
};


should be self explanitory, create a local class that takes care of cleanup and have its destructor do all the messy work for you, the only problem is that you need to somehow make it aware of local variables to clean that can be combated by simply putting all variables to be cleant inside the janitor and if you don't like the clunky janitor_instance.my_variable syntax simply create references in the function refering to the vars inside the janitor. And no you don't need to wory about bloat refrences can occupy 0space.

Share this post


Link to post
Share on other sites
_the_phantom_    11250
*chuckles* I had an arguement about early returns with my C++ lecturer when I first went to Uni, she argued that you should only have one exit point I argued it was cleaner to bail when you needed to rather than nesting ifs etc... in the end, for the sake of marks I rewrote it to conform to her ideal, but it still amuses me just how balistic she went over it, heh

Share this post


Link to post
Share on other sites
Andrew Russell    1394
Quote:
Original post by _the_phantom_
*chuckles* I had an arguement about early returns with my C++ lecturer when I first went to Uni, she argued that you should only have one exit point I argued it was cleaner to bail when you needed to rather than nesting ifs etc... in the end, for the sake of marks I rewrote it to conform to her ideal, but it still amuses me just how balistic she went over it, heh

Good to know that software developers everywhere get such a <sarc>good, relevent, and up-to-date</sarc> education at University (to go with that shiny napkin).

*grumble*

Share this post


Link to post
Share on other sites
ApochPiQ    23064
Quote:
Original post by _the_phantom_
*chuckles* I had an arguement about early returns with my C++ lecturer when I first went to Uni, she argued that you should only have one exit point I argued it was cleaner to bail when you needed to rather than nesting ifs etc... in the end, for the sake of marks I rewrote it to conform to her ideal, but it still amuses me just how balistic she went over it, heh



I had a similar experience once. I came away from the debate with a distinct impression that the instructor didn't know much about real code, so I vowed to write all of my code in the most intensely complicated, obfuscated, and arcane manner possible. The funny thing was, in a lot of cases, my implementations ended up being shorter and faster than what would have been obtained by following the "recommended steps for solution" in the course material. Eventually my code got so hideous that the instructor quit actually reading it (and, thereby, quit complaining about it), at which point I went back to solving things however I darned well felt like it. I got away with the entire thing because the course grading structure required that projects receive full credit if they behaved to specs and didn't exhibit any blatantly horrible problems.

After that, I figured I'd never be able to pull that stunt off again, and walked away from formal CS/SE education for good.

Share this post


Link to post
Share on other sites
snk_kid    1312
Quote:
Original post by _the_phantom_
well, this was back in 1998... I'm hoping things will have improved slight when I try again in september this year [smile]

put it this way, if it hasnt i'll grumble about it plenty in my journal, heh


Indeed when i was at uni i never took what lecturers say as the final/definitive word on a subject. Most (not all) of them haven't got a clue, they just regurgitate some crappy beginners book and don't know anything beyond that, don't have any real experience either.

Try correcting them or suggest a better alternative they wont have any of it.

I don't think it will ever change either.

Share this post


Link to post
Share on other sites
iMalc    2466
Quote:
Original post by ApochPiQ
Quote:
Original post by _the_phantom_
*chuckles* I had an arguement about early returns with my C++ lecturer when I first went to Uni, she argued that you should only have one exit point I argued it was cleaner to bail when you needed to rather than nesting ifs etc... in the end, for the sake of marks I rewrote it to conform to her ideal, but it still amuses me just how balistic she went over it, heh



I had a similar experience once. I came away from the debate with a distinct impression that the instructor didn't know much about real code, so I vowed to write all of my code in the most intensely complicated, obfuscated, and arcane manner possible. The funny thing was, in a lot of cases, my implementations ended up being shorter and faster than what would have been obtained by following the "recommended steps for solution" in the course material. Eventually my code got so hideous that the instructor quit actually reading it (and, thereby, quit complaining about it), at which point I went back to solving things however I darned well felt like it. I got away with the entire thing because the course grading structure required that projects receive full credit if they behaved to specs and didn't exhibit any blatantly horrible problems.

After that, I figured I'd never be able to pull that stunt off again, and walked away from formal CS/SE education for good.
ROFL[lol]!!!
That's sooo cool! I so wish I could have done something like that, you ledgend!

I myself will not use an early return when it would be just as clear not doing so.

Share this post


Link to post
Share on other sites
Nemesis2k2    1045
I'm in a good position right now, where the teachers I have for programming classes accept that I know more about coding than they do, and pretty much let me write things however I want to. That said, I did get some useful tips out of this course back at the beginning that have changed the way I do certain things.

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this