vb.net - 正确的编程——一个函数应该在所有代码路径上返回一个值吗?

标签 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

最佳答案

根据一般经验,是的,您应该确保所有执行路径都返回东西,即使那个东西Nothing .我之所以这样说,主要是因为有几种编程语言甚至无法编译,除非您遵守这一点,所以您不妨养成这个习惯。

但是话虽如此,在这种特定情况下,我们可能想要进行一些验证,并且实际上在我们的 _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

关于vb.net - 正确的编程——一个函数应该在所有代码路径上返回一个值吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30158227/

相关文章:

Vb.Net - 基于模式复制文件

function - 在 Python 中的函数之间传递值的最佳实践

.net - 为什么ShowDialog总是返回DialogResult.Cancel?

c++ - vector 返回空c++

.net - 如何在设置为只读的 .NET TextBox 中选择(突出显示)文本?

vb.net - 关于泛型的初学者问题

.net - 在 .NET 平台上创建 RTSP 视频流

c# - 使用 Telerik 导出到 Excel (XLSX) 时如何解释集合?

c# - 处理未使用的 IDisposable 返回值是否重要?

exception - 我应该返回 null 还是抛出异常?