Too many return-statements = bad style?

Michael Geary Mike at DeleteThis.Geary.com
Fri Jul 9 18:25:59 CEST 2004


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

Or, you could write it this way (to me this is less readable, but still
better than the original):

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

-Mike





More information about the Python-list mailing list