Too many return-statements = bad style?

george young gry at ll.mit.edu
Fri Jul 9 14:14:11 EDT 2004


On Fri, 9 Jul 2004 09:25:59 -0700
"Michael Geary" <Mike at DeleteThis.Geary.com> threw this fish to the penguins:

> Roy Smith wrote:
> 
> > def getFoo (i):
> >    if blah:
> >       if i == 4:
> >          return 1
> >       else:
> >          return 2
> >    return 3
> 
> That still has some unnecessary nesting. :-) Since you're returning 3
> whenever blah is false, there's no need to nest the other if statement
> inside the "if blah". Simply reverse the test.
> 
> Also, I generally don't like "if...return...else...return" constructs
> because the "else" is redundant.
> 
> Here is the same logic in a form that I find much easier to follow:
> 
> def getFoo (i):
>     if not blah: return 3
>     if i == 4: return 1
>     return 2

Hmm... contrariwise, I find:

def getFoo(i):
    if not blah: return 3
    elif i == 4: return 1
    else: return 2

more compelling, the if--elif--else emphasizing that these are three
possible outcomes; the last return is in the same logical level as
the other returns, so it seems right that it be in a similar syntactic
position.
[I don't care if the 'return' is on the same or separate line, sometimes
 I use one for brevity, sometimes the other for clarity]

-- George Young
-- 
"Are the gods not just?"  "Oh no, child.
What would become of us if they were?" (CSL)



More information about the Python-list mailing list