[Python-ideas] If branch merging
Stefan Behnel
stefan_ml at behnel.de
Mon Jun 8 06:43:52 CEST 2015
Cory Beutler schrieb am 07.06.2015 um 05:03:
> *Examples of use:*
> *Duplicate code in if-chains may be reduced:*
> # Old Version
> if a == b:
> print ('a == b')
> foo() # <-- duplicate code
> elif b == c:
> print ('b == c')
> foo() # <-- duplicate code
> elif c == d:
> print ('c == d')
> foo() # <-- duplicate code
>
> # New Version
> if a == b:
> print ('a == b')
> elif b == c:
> print ('b == c')
> elif c == d:
> print ('c == d')
> also:
> foo() # <-- No longer duplicated
I think this is best done by extracting it into a function, e.g.
def good_name_needed():
if a == b:
print('a == b')
elif b == c:
print('b == c')
elif c == d:
print('c == d')
else:
# nothing to do here
return
foo() # <-- No longer duplicated
Usually, in real code, the call to foo() will have some kind of relation to
the previous if-chain anyway, so a good name for the whole function
shouldn't be all to difficult to find.
Stefan
More information about the Python-ideas
mailing list