是否有特别的理由偏爱跨入多个区块而不是捷径?例如,采用以下两个函数来评估多个条件。第一个示例进入每个块,而第二个示例捷径。这些示例在Python中进行,但问题不限于Python。它也过于琐碎。
def some_function():
if some_condition:
if some_other_condition:
do_something()
Run Code Online (Sandbox Code Playgroud)
与
def some_function():
if not some_condition:
return
it not some_other_condition:
return
do_something()
Run Code Online (Sandbox Code Playgroud)
支持第二个使代码更易于阅读。在您的示例中并没有那么明显,但请考虑:
def some_function()
if not some_condition:
return 1
if not some_other_condition:
return 2
do_something()
return 0
Run Code Online (Sandbox Code Playgroud)
与
def some_function():
if some_condition:
if some_other_condition:
do_something()
return 0
else:
return 2
else:
return 1
Run Code Online (Sandbox Code Playgroud)
即使该函数没有针对“失败”条件的返回值,使用第二种方式编写函数也可以使放置断点和调试更加容易。在您最初的示例中,如果您想知道由于some_condition或some_other_condition失败而导致代码未运行,您将在哪里放置断点?
| 归档时间: |
|
| 查看次数: |
3417 次 |
| 最近记录: |