If/then style question

Francesco fal at togliquesto.fastwebnet.it
Sat Dec 18 06:29:31 EST 2010


On 17/12/2010 0.51, Steven D'Aprano wrote:
> Don't get me wrong... spaghetti code is*bad*. But there are other ways
> of writing bad code too, and hanging around inside a function long after
> you've finished is also bad:
>
> def function(arg):
>      done = False
>      do_something()
>      if some_condition:
>          result = "finished"
>          done = True
>      if not done:
>          do_something_else()
>          if another_condition:
>              result = "now we're finished"
>              done = True
>      if not done:
>          do_yet_more_work()
>          if third_condition:
>              result = "finished this time for sure"
>              done = True
>      if not done:
>          for i in range(1000000):
>              if not done:
>                  do_something_small()
>                  if yet_another_condition:
>                      result = "finally done!"
>                      done = True
>      return result
>
> It's far more complicated than it need be, and does*lots*  of unnecessary
> work. This can be written more simply and efficiently as:
>
> def function(arg):
>      do_something()
>      if some_condition:
>          return "finished"
>      do_something_else()
>      if another_condition:
>          return "now we're finished"
>      do_yet_more_work()
>      if third_condition:
>          return "finished this time for sure"
>      for i in range(1000000):
>          do_something_small()
>          if yet_another_condition:
>              return "finally done!"

I agree to your point, but I'm afraid you chose a wrong example (AFAIK, and that's not much).
Sure, the second version of function(arg) is much more readable, but why do you think the first one would do "*lots*  of unnecessary 
work"?
All the overhead in that function would be:
   if some_condition, three IF tests, and you know that's NOT a lot!
   if no conditions were met, (worst case) the first version would return an exception (unless result was globally defined) while 
the second would happily return None. Apart from this, the overhead in the first one would amount to one million IF tests, again not 
a lot these days. I don't think I would rewrite that function, if I found it written in the first way...
I don't mean that the fist example is better, just I'm sure you could imagine a more compelling proof of your concept.
Maybe there's something I don't know... in that case, please enlighten me!

Francesco



More information about the Python-list mailing list