我正在做一些碰撞检测,我非常想在两个不同的上下文中使用相同的函数。在一种情况下,我希望它类似于
def detect_collisions(item, others):
return any(collides(item, other) for other in others)
在另一个方面,我希望它是
def get_collisions(item, others):
return [other for other in others if collides(item, other)]
我真的很讨厌在这里写两个函数的想法。只是保持他们的名字直截了当是一个岔路口,而使碰撞检测的界面复杂化是另一个问题。所以我在想:
def peek(gen):
try:
first = next(gen)
except StopIteration:
return False
else:
return it.chain((first,), gen)
def get_collisions(item, others):
get_collisions.all = peek(other for other in others if collides(item, other))
return get_collisions.all
现在,当我只想进行检查时,我可以说:
if get_collisions(item, others):
# aw snap
或者
if not get_collisions(item, others):
# w00t
在我真正想要检查它们的其他上下文中,我可以这样做:
if get_collisions(item, others):
for collision in get_collisions.all:
# fix it
在这两种情况下,我都不会做比我需要的更多的处理。
我认识到这比前两个函数的代码更多,但它也具有以下优点:
将我的碰撞检测界面保持为一棵树,节点位于顶层而不是中间层。这似乎更简单。
用一个方便的窥视功能连接自己。如果我再次使用它,那么我实际上会编写更少的代码。(回应YAGNI,如果我有,我会的)
所以。如果你是众所周知的杀人狂,知道我住在哪里,如果我写了上面的代码,我会期待你的来访吗?如果是这样,您将如何处理这种情况?