【问题标题】:Function with multiple exit-points: is it a good way to do?具有多个出口点的功能:这是一个好方法吗?
【发布时间】:2011-12-20 16:34:35
【问题描述】:

在使用 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

请分享你的想法。

【问题讨论】:

    标签: coding-style code-readability


    【解决方案1】:

    几十年来,我一直使用“if (badParameters) then exit”的编码风格。如果不出意外,执行工作的实际“长代码”不会被巨大的“if/then/else”阶梯推离编辑窗口的右侧。阶梯使代码看起来比实际更混乱、更复杂,并妨碍了可读性。

    【讨论】:

      【解决方案2】:

      在处理错误情况时退出函数肯定更好。原因是通过避免无休止的嵌套 if 来提高可读性。

      【讨论】:

        猜你喜欢
        • 2015-05-09
        • 2020-01-31
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-11-05
        • 2012-07-20
        • 1970-01-01
        相关资源
        最近更新 更多