Too many return-statements = bad style?
steve_thompson at prodigy.net
Wed Jul 14 16:13:50 CEST 2004
Marco Aschwanden <PPNTWIMBXFFC <at> spammotel.com> writes:
> I prefer multiple returns instead of increasingly complex nesting. Obviously
> having too many returns (or too much nesting) is showing that you've got a
> function which is in need of splitting - I think 5 and especially 7 is a lot,
> but it depends on the function. I also like having the conditions such, that the
> short code is at the top of the if-else clause, while some programming
> guidelines claim you should write the most common cause first (even if that's
> considerably longer than the uncommon one).
I guess that I'm going to be the only voice of dissenting opinion here
Having programmed in many languages, I've picked up what I would like
to think are some of the best practices in software development, and
single entry/single exit, which is enforced in the Eiffel language at
least, is one such technique. The promise of this practice is that it
forces you to factor your code, and in fact I've found it unusual when
adhering to this to produce routines longer than about a dozen lines.
I should mention that the Eiffel language also does not support gotos
of any kind, and so in sharp contrast to a 'C' project I was forced to
maintain several years ago, one does not encounter functions that are
thousands of lines long.
These days, all of my Python routines are single entry/single exit.
It is a practice that to me is a mark of good software engineering, as
is never using 'continue' (why does this useless artifact survive from
language to language?) and leaving loops only when the loop condition
is met. At the end of the day this means my code is easy to read,
easy to follow, and fairly well factored.
And for those folks that actually view many exits as a Good Thing, I
would argue that increasing the cyclomatic complexity of any piece of
code is by definition the very antithesis of good software
Best regards to all,
More information about the Python-list