偶尔我会遇到这样的情况,我写了一些代码,但根据它的逻辑,某条路径是不可能的。例如:
activeGames = [10, 20, 30]
limit = 4
def getBestActiveGameStat():
if not activeGames: return None
return max(activeGames)
def bah():
if limit == 0: return "Limit is 0"
if len(activeGames) >= limit:
somestat = getBestActiveGameStat()
if somestat is None:
print "The universe has exploded"
#etc...
宇宙爆炸线会走什么?如果 limit 为 0,则函数返回。如果 len(activeGames) >= limit
,则必须至少有一个事件游戏,因此 getBestActiveGameStat()
不能返回 None。那么,我应该检查一下吗?
同样的事情也发生在 while 循环中,它总是在循环中返回:
def hmph():
while condition:
if foo: return "yep"
doStuffToMakeFooTrue()
raise SingularityFlippedMyBitsError()
既然我“知道”这是不可能的,那么那里应该有什么东西吗?
最佳答案
If len(activeGames) >= limit, then there must be at least one active game, so getBestActiveGameStat() can't return None. So, should I even check for it?
有时我们会犯错误。您现在可能有一个程序错误——或者以后有人会创建一个。
这些错误可能会导致异常或单元测试失败。但是调试是昂贵的;有多种方法来检测错误是很有用的。
快速编写的断言语句可以向人类读者表达预期的不变性。在调试时,失败的断言可以快速查明错误。
Sutter 和 Alexandrescu 在“C++ 编码标准”中解决了这个问题。尽管有标题,但他们的论点和指导方针与语言无关。
Assert liberally to document internal assumptions and invariants ... Use assert or an equivalent liberally to document assumptions internal to a module ... that must always be true and otherwise represent programming errors.
例如,如果 switch
语句中的 default
情况不能发生,则添加带有 assert(false) 的情况。
关于language-agnostic - 处理 "impossible"代码路径的优雅方式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3834121/