If/then style question
Steve Holden
steve at holdenweb.com
Fri Dec 17 00:19:42 EST 2010
On 12/16/2010 11:32 PM, Carl Banks wrote:
> On Dec 16, 2:56 pm, Ryan Kelly <r... at rfk.id.au> wrote:
>> On Thu, 2010-12-16 at 21:49 +0000, John Gordon 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.
>>
>>> 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?
>>
>> "one entry, one exit" has its good points, but it's *way* overquoted and
>> overused.
>>
>> Do you raise any exceptions? Do you call any functions that might raise
>> exceptions? If so, you've got multiple exit points already.
>>
>> I think this style a lot more important in a language like C where you
>> have to be super-careful about cleaning up after yourself. The single
>> exit point makes it easier to verify that all cleanup tasks have been
>> performed. Assuming you're using "with" or "try-finally" then you just
>> don't need such guarantees in python.
>
> Even without the cleanup issue, sometimes you want to edit a function
> to affect all return values somehow. If you have a single exit point
> you just make the change there; if you have mulitple you have to hunt
> them down and change all of them--if you remember to. I just got bit
> by that one.
>
> It's a trade-off. Readability and/or conciseness versus error
> robustness. I tend to go for the former but mileage varies.
>
Heaven forfend you should just wrap the existing function inside another
one which takes its name, if all its returns need to be altered.
regards
Steve
--
Steve Holden +1 571 484 6266 +1 800 494 3119
PyCon 2011 Atlanta March 9-17 http://us.pycon.org/
See Python Video! http://python.mirocommunity.org/
Holden Web LLC http://www.holdenweb.com/
More information about the Python-list
mailing list