【发布时间】:2021-05-12 02:27:27
【问题描述】:
我有两个非常相似的函数,它们几乎是重复的,只是条件相反。我想遵循 DRY 模式,但我之前在某处读过,将布尔值传递给函数以改变行为是一种不好的做法(因为它难以维护)。我在这里编写干净且不重复的代码的最佳选择是什么?谢谢
def find_upper_tangent(left, right):
l_idx = get_rightmost(left)
r_idx = get_leftmost(right)
upper_tangent_left = False
upper_tangent_right = False
prev_slope = get_slope(left[l_idx], right[r_idx])
while not upper_tangent_left or not upper_tangent_right:
while not upper_tangent_left:
# move counter clockwise
next_slope = get_slope(left[(l_idx - 1) % len(left)], right[r_idx])
if next_slope < prev_slope:
l_idx = (l_idx - 1) % len(left)
prev_slope = next_slope
upper_tangent_right = False
else:
upper_tangent_left = True
while not upper_tangent_right:
# move clockwise
next_slope = get_slope(left[l_idx], right[(r_idx + 1) % len(right)])
if next_slope > prev_slope:
r_idx = (r_idx + 1) % len(right)
prev_slope = next_slope
upper_tangent_left = False
else:
upper_tangent_right = True
return l_idx, r_idx
def find_lower_tangent(left, right):
l_idx = get_rightmost(left)
r_idx = get_leftmost(right)
lower_tangent_left = False
lower_tangent_right = False
prev_slope = get_slope(left[l_idx], right[r_idx])
while not lower_tangent_left or not lower_tangent_right:
while not lower_tangent_left:
# move clockwise
next_slope = get_slope(left[(l_idx + 1) % len(left)], right[r_idx])
if next_slope > prev_slope:
l_idx = (l_idx + 1) % len(left)
prev_slope = next_slope
lower_tangent_right = False
else:
lower_tangent_left = True
while not lower_tangent_right:
# move counter clockwise
next_slope = get_slope(left[l_idx], right[(r_idx - 1) % len(right)])
if next_slope < prev_slope:
r_idx = (r_idx - 1) % len(right)
prev_slope = next_slope
lower_tangent_left = False
else:
lower_tangent_right = True
return l_idx, r_idx
【问题讨论】:
标签: design-patterns refactoring dry