If/then style question
John Gordon
gordon at panix.com
Thu Dec 16 16:49:07 EST 2010
(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.
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?
Thanks.
--
John Gordon A is for Amy, who fell down the stairs
gordon at panix.com B is for Basil, assaulted by bears
-- Edward Gorey, "The Gashlycrumb Tinies"
More information about the Python-list
mailing list