Too many return-statements = bad style?
Roy Smith
roy at panix.com
Fri Jul 9 09:39:22 EDT 2004
Marco Aschwanden <PPNTWIMBXFFC at spammotel.com> wrote:
> Through books I learned, that there should be only 1 return statement in a
> function. This makes for clear code - they said. I tried to stick to this
> principle for a very long time... ending up with deeper and deeper nested
> if-then-else-clauses and hided code-sections with clever if-then-clauses
> when the return value was already clear or when the code was not eligible
> for this specific return value:
You're talking about "Single Entry, Single Exit". It was a style of
coding that used to be popular. I hate it, for exactly the reasons you
state above. http://c2.com/cgi/wiki?SingleFunctionExitPoint has some
interesting things to say on that.
I even go so far as to intentionally write multiple-exit functions
during refactoring because they are often a neat way to clean up messy
logic. Let's say I've got:
for i in list:
if blah:
if i == 4:
foo = 1
else:
foo = 2
else:
foo = 3
that's a mess to read (especially if it's further embedded inside some
other complex logic). What I'll do is force that little bit of uglyness
down into a multi-return function:
def getFoo (i):
if blah:
if i == 4:
return 1
else:
return 2
return 3
and then just write in my main-line code:
for i in list:
foo = getFoo (i)
More information about the Python-list
mailing list