On 11/05/2007, at 4:23 PM, Tim Leslie wrote:
As a general rule each function should have a single return statement,
Personally, I don't subscribe to this 'rule' at all (especially if
you want to check preconditions upon function entry, when it's
perfectly sane to return early). To me, if it makes sense to return
early from a control-flow point of view, I return early. If the
function doesn't need to do any more work, just return early. I
don't think adding another mutable variable at the start of the
function makes the code cleaner at all: you're introducing another
yet another variable and add more control paths to the function if
you do that.
The one complication this adds is cleanup. In C, you can use goto.
In C++, use RAII. In languages with try/finally exception handling,
you can put cleanup code in a finally block. Here's an example
(Objective-C syntax, although it's obviously easily carried across
into Java/Python/etc:
FILE* foo = NULL;
@try
{
foo = fopen("/tmp/blahblah", "r");
if(thingy) return;
}
@finally
{
// Will always get executed, even if returning early
if(foo != NULL) fclose(foo);
}
Using a finally block also has the added advantage that your
resources will get cleaned up if something you call in your function
decides to throw an exception, which isn't the case if you use an
extra return value variable.
This technique may turn out to be less maintainable than adding a
simple mutable variable, of course. I judge this on a case-by-case
basis; no need to subscribe to dogma.
(Note: Don't use a finaliser in garbage-collected languages such as
Python or Java to cleanup resources and simulate C++ RAII, because
the finalisers sometimes won't be called under certain
circumstances. Consult your local language lawyer about this :).
--
% Andre Pang : trust.in.love.to.save <http://www.algorithm.com.au/>
_______________________________________________
coders mailing list
[email protected]
http://lists.slug.org.au/listinfo/coders