功能与多个出口点:这是一个好方法



在使用VBScript编程期间,我在函数开始执行操作之前编写了许多错误检查代码。所以,如果一些先决条件没有满足,那么我做"退出功能"。例如:

public fucnton func
   if not condition then
     func = -1
     exit function
   End If
   'Other conditions with exit functions
   'Then long code goes here
   ..........
   ..........
   ..........
   func = res
End Function

所以,我可以在多个点退出函数。这是一个好方法吗?在这种情况下,我将得到if语句的长else分支

也许这样写更好:

public fucnton func
    if not condition then
        func = -1
    Else
        'Then long code goes here
        ..........
        ..........
        ..........
    End If  
End Function

请分享你的想法。

几十年来我一直使用'if (badParameters) then exit'的编码风格。如果没有别的,实际的"长代码",做的工作并没有推到右边的编辑窗口通过一个巨大的"If/then/else"梯子。梯子使代码看起来比实际情况更混乱、更复杂,并且妨碍了可读性。

最好在处理错误情况时退出函数。这样做的原因是避免了无穷无尽的嵌套if语句,从而提高了可读性。

最新更新