Am 16.12.2010 22:49, schrieb John Gordon:
(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

            else:
        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.





The advantage in latter case is fewer operations, because you can skip the assignments,
and it is more readable.

The "one entry, one exit" is an advice. Not a law.
Your code is OK.

As long as it works ;-)


P.S.:
Sorry, I could not resist:
return bad1 if some_bad_condition else bad2 if some_other_bad_condition else bad3 if yet_another_bad_condition else good1 if do_some_useful_stuff() else good1
Or consider this:
return [x for x,y in ((bad1,some_bad_condition),(bad2,some_other_bad_condition),(bad3,yet_another_bad_condition),(good1,do_some_useful_stuff() or True)) if x][0]

Neither self explanatory nor readable :-(
--
http://mail.python.org/mailman/listinfo/python-list

Reply via email to