If/then style question

Grant Edwards invalid at invalid.invalid
Thu Dec 16 17:13:40 EST 2010


On 2010-12-16, John Gordon <gordon at panix.com> wrote:
> (This is mostly a style question, and perhaps one that has already been
> discussed elsewhere.  If so, a pointer to that discussion will be
> appreciated!)
>
> When I started learning Python, I wrote a lot of methods that looked like
> this:
>
>
>   def myMethod(self, arg1, arg2):
>     if some_good_condition:
>       if some_other_good_condition:
>         if yet_another_good_condition:
>           do_some_useful_stuff()
>           exitCode = good1
>         else:
>           exitCode = bad3
>       else:
>         exitCode = bad2
>     else:
>       exitCode = bad1
>     return exitCode
>
>
> But lately I've been preferring this style:
>
>
>   def myMethod(self, arg1, arg2):
>
>     if some_bad_condition:
>       return bad1
>
>     elif some_other_bad_condition:
>       return bad2
>
>     elif yet_another_bad_condition:
>       return bad3
>
>     do_some_useful_stuff()
>     return good1
>
> I like this style more, mostly because it eliminates a lot of
> indentation.

There's nothing inherently wrong with indentation, but in this case
the latter style is a _lot_ easier to read (and modify without
breaking).

> However I recall one of my college CS courses stating that "one
> entry, one exit" was a good way to write code, and this style has
> lots of exits.
>
> Are there any concrete advantages of one style over the other?

I think the check/exit style is far more readable.

It can trip you up if there is cleanup stuff that needs to happen
before you return from the function.  In that case putting the whole
function in a try statement and raising exceptions for the "bad
conditions" works nicely.  Then you get the more readable style of the
check/exit style, plus the advantage of a single exit (it's easy to
verify visually that all the required cleanup is happening).

-- 
Grant Edwards               grant.b.edwards        Yow! I want a WESSON OIL
                                  at               lease!!
                              gmail.com            



More information about the Python-list mailing list