Coding style 反转if语句

Coding style 反转if语句,coding-style,Coding Style,有没有特别的理由支持走多个街区而不是走捷径?例如,以以下两个函数为例,其中计算了多个条件。第一个示例是进入每个块,而第二个示例是捷径。这些示例是用Python编写的,但问题并不局限于Python。它也过于琐碎了 def some_function(): if some_condition: if some_other_condition: do_something() vs 支持第二个选项可以使代码更易于阅读。在您的示例中,这并不明显,但请考虑:

有没有特别的理由支持走多个街区而不是走捷径?例如,以以下两个函数为例,其中计算了多个条件。第一个示例是进入每个块,而第二个示例是捷径。这些示例是用Python编写的,但问题并不局限于Python。它也过于琐碎了

def some_function():
    if some_condition:
        if some_other_condition:
            do_something()
vs


支持第二个选项可以使代码更易于阅读。在您的示例中,这并不明显,但请考虑:

def some_function()
    if not some_condition:
       return 1
    if not some_other_condition:
       return 2
    do_something()
    return 0
vs

即使函数没有“失败”条件的返回值,使用反转ifs方式编写函数也会使放置断点和调试更容易。
在您最初的示例中,如果您想知道代码是否因为某个条件或某个其他条件失败而没有运行,您会将断点放在哪里?

因为第二个条件有时看起来更漂亮?我的许多教授都会喜欢前者。他们在功能/方法的中间没有回报。
def some_function()
    if not some_condition:
       return 1
    if not some_other_condition:
       return 2
    do_something()
    return 0
def some_function():
    if some_condition:
       if some_other_condition:
           do_something()
           return 0
       else:
           return 2
    else:
        return 1