正确编程 - 函数是否应在所有代码路径上返回值?

时间:2015-05-11 00:52:41

标签: vb.net return-value

我的VB.Net类的构造函数传递了Enum属性的值。如果我在这个使用Select Case语句的类中创建一个方法,那么包含Case Else行(永远不会被执行)的编程是否合适?我理解,只是想知道什么是"正确"编程。

Public Enum eList
    one = 1
    two = 2
    three = 3
End Enum

Public Class Class1
    Private _eValue As eList

    Public Sub New(ByVal ePassed As eList)
        _eValue = ePassed
    End Sub

    Public Function SomeMethod() As Object
        Select Case _eValue
            '(all eList items accounted for below)
            Case eList.one
                'do something
            Case eList.two
                'do something else
            Case eList.three
                'do another thing
            Case Else
                '  should I put a Return <value> line here?
        End Select
        '  and should I also put a Return <value> line here?
    End Function

End Class

2 个答案:

答案 0 :(得分:5)

作为一般的经验法则,是的,您应该确保所有执行路径都返回某些内容,即使某些内容Nothing。我主要是这样说的,因为除非你遵守这个规则,否则几种编程语言甚至都不会编译,所以你也可以养成习惯。

但话虽如此,在这种特定情况下,我们可能希望进行一些验证,并且在Throw未设置为有效值的任何时候实际_eValue都是例外在Enum。这里的建议很好,并且建议在这里和其他场景中应用。

确保我们验证输入是非常重要的。

在很多情况下,单次返回可以使我们的代码更具可读性。所以,考虑让你的函数看起来像这样:

Public Function SomeMethod() As Object
    Dim SomeReturnValue As Object = Nothing
    Select Case _eValue
        Case eList.one
            SomeReturnValue = New Something()
        Case eList.two
            SomeReturnValue = New SomethingElse()
        Case eList.three
            SomeReturnValue = New YetSomeOtherThing()
        Case Else
            Throw New Exception("Invalid State Exception: _eValue property in an invalid state.")
    End Select
    Return SomeReturnValue
End Function

答案 1 :(得分:4)

您问题的具体答案是肯定的,函数的所有可能代码路径都应返回一个值。如果select case中的每个case返回一个值而else也返回了一个值,那么所有路径都会被覆盖。我认为,无论你是否应该在其他情况下或在功能结束时获得回报,这都是个人品味。一些开发人员更喜欢在函数末尾只有一个return语句。