language-agnostic - 处理 "impossible"代码路径的优雅方式

标签 language-agnostic coding-style

偶尔我会遇到这样的情况,我写了一些代码,但根据它的逻辑,某条路径是不可能的。例如:

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/

相关文章:

android - 主题中的 TextAppearance

php - if语句条件优化

c# - 将只运行一次的代码移动到函数中是否可以?

algorithm - 是否有一个完全在线的 IDE 来测试简单的算法

language-agnostic - 加密安全的附加哈希函数

php - 嵌套条件与返回意外结果

c++ - : (a == 0) vs (0 == a)的优缺点

java - 理解java中的DI

python - 从列表中过滤掉附近的点

algorithm - 给定边长的网格多边形面积