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. I'm not a PEP-8 pedant by any means, but I think that the first section of PEP-8 contains the best advice I've ever read about programming language style. In fact, I'm going to quote it right here: A Foolish Consistency is the Hobgoblin of Little Minds ====================================================== One of Guido's key insights is that code is read much more often than it is written. The guidelines provided here are intended to improve the readability of code and make it consistent across the wide spectrum of Python code. As PEP 20 says, "Readability counts". ...snip... But most importantly: know when to be inconsistent -- sometimes the style guide just doesn't apply. When in doubt, use your best judgment. Look at other examples and decide what looks best. And don't hesitate to ask! In your example, the first style is difficult to read wile the second style is easy to read. You don't need any further justification for preferring the latter. Cheers, Ryan -- Ryan Kelly http://www.rfk.id.au | This message is digitally signed. Please visit r...@rfk.id.au | http://www.rfk.id.au/ramblings/gpg/ for details
signature.asc
Description: This is a digitally signed message part
-- http://mail.python.org/mailman/listinfo/python-list