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

JDG*_*nts 2 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
Run Code Online (Sandbox Code Playgroud)

nhg*_*rif 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
Run Code Online (Sandbox Code Playgroud)