所以我认为我很聪明并且DRY通过从一堆类似的函数中删除一堆公共代码并将它们转换为所有在一个地方定义的辅助函数。 (见GitHub diff)这样他们都可以从一个地方修改。 (见another GitHub diff)
原来是
func_A(stuff):
if stuff == guard_condition:
return early
things = boilerplate + stuff
do A-specific stuff(things)
return late
func_b(stuff):
if stuff == guard_condition:
return early
things = boilerplate + stuff
do B-specific stuff(things)
return late
我将其改为
_helper(stuff):
if stuff == guard_condition:
return early
things = boilerplate + stuff
return things
func_A(stuff):
things = _helper(stuff)
do A-specific stuff(things)
return late
func_B(stuff):
things = _helper(stuff)
do B-specific stuff(things)
return late
但后来我尝试了,并意识到由于我已经将早期的回报("警卫"?)转移到帮助函数中,它们当然不再有效。现在我可以轻松地将一些代码添加到原始函数中来处理这些情况,但似乎没有办法在没有将复杂性再次移回单个函数并重复的情况下这样做。
处理这种情况最优雅的方式是什么?
答案 0 :(得分:2)
您可以将a-specific stuff
和b-specific stuff
提取到核心函数,这些函数将传递给您的辅助函数。然后帮助者将决定是否调用核心函数:
_helper(stuff, _core_func):
if stuff == guard_condition:
return early
things = boilerplate
return _core_func(things)
_a_core(_things):
do a-specific stuff
return late
_b_core(_things):
do b-specific stuff
return late
func_A(stuff):
return _helper(stuff, _a_core)
func_B(stuff):
return _helper(stuff, _b_core)
在了解从助手返回的价值之前的早期回答
我会给_helper
一个返回值:
_helper(stuff):
if guard:
return False
boilerplate
return True
func_a(stuff):
if _helper():
do a-specific stuff
return
func_b(stuff):
if _helper():
do b-specific stuff
return
答案 1 :(得分:2)
这有帮助吗?
def common_stuff(f):
def checked_for_guards(*args, **kwargs):
if stuff == guard_condition:
return early
things = boilerplate
else:
return f(*args, **kwargs)
return checked_for_guards
@common_stuff
def func_A(stuff):
do A-specific stuff(things)
return late
@common_stuff
def func_b(stuff):
do B-specific stuff(things)
return late