7

Is there a particular reason to favor stepping into multiple blocks vs. short cutting? For instance, take the following two functions in which multiple conditions are evaluated. The first example is stepping into each block, while the second example short cuts. The examples are in Python, but the question is not restricted to Python. It is overly trivialized as well.

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

vs.

def some_function():
    if not some_condition:
        return
    it not some_other_condition:
        return
    do_something()
4

1 回答 1

7

偏爱第二个使代码更易于阅读。在您的示例中并不那么明显,但请考虑:

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

即使函数没有“失败”条件的返回值,使用反向 ifs 方式编写函数也可以更轻松地放置断点和调试。在您的原始示例中,如果您想知道您的代码是否因为 some_condition 或 some_other_condition 失败而未运行,您将在哪里放置断点?

于 2012-11-28T03:43:21.823 回答