If/then style question

Steven D'Aprano steve+comp.lang.python at pearwood.info
Sun Dec 19 03:33:51 EST 2010


On Sat, 18 Dec 2010 19:59:45 -0800, Carl Banks wrote:

> On Dec 17, 12:23 am, Steven D'Aprano <steve
> +comp.lang.pyt... at pearwood.info> wrote:
>> On Thu, 16 Dec 2010 20:32:29 -0800, Carl Banks wrote:
>> > 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.
>>
>> If your function has so many exit points that you can miss some of them
>> while editing, your function is too big, does too much, or both.
> 
> Sanctimonious much?  In the real world, people "miss things" and "make
> mistakes" and not necessarily because they are working on something too
> complex to handle.  It happens.


Really? I had no idea. I've never made a misteak, I asumed evrybody else 
was equally brilliant. No, wait, there was that one time...

*wink*

Of course people make mistakes. So what's your point?

The point I was trying to make is that rather than encouraging an idiom 
(only one return statement, even if the algorithm is more clearly written 
with multiple exists) that leads to more complex, less efficient code 
just in case you might someday need to modify the return result, there 
are simple alternatives that avoid the need for anti-patterns like copy-
and-paste coding or enforced single exit point. I gave two: 

- refactor the complex code so that it's less complex (e.g. instead of 20 
exit points, which makes it easy to miss one or two, refactor it so there 
are two or three exit points); or if that's not practical:

- wrap it in a decorator that performs the post-processing you need.

Both can be simple, effective and Pythonic. Neither require the coder to 
use an artificial idiom just in case of some future need. The decorator 
solution works even if you don't have access to the source code, or if 
the function is a complex black box that nobody understands well enough 
to touch.



-- 
Steven



More information about the Python-list mailing list