当前位置:  开发笔记 > 编程语言 > 正文

什么时候可以在VB.Net中使用GoTo语句?

如何解决《什么时候可以在VB.Net中使用GoTo语句?》经验,为你挑选了3个好方法。

我有进程需要在数据库中创建一堆记录,如果出现任何问题,请将所有内容回滚.我想要做的是:

Public Structure Result
    Public Success as Boolean
    Public Message as String
End Structure

Private _Repository as IEntityRepository

Public Function SaveOrganization( _
    ByVal organization As rv_o_Organization) As Result
    Dim result = Result.Empty

    _Repository.Connection.Open()
    _Repository.Transaction = _Repository.Connection.BeginTransaction()

    ''//Performs validation then saves it to the database
    ''// using the current transaction
    result = SaveMasterOrganization(organization.MasterOrganization)
    If (Not result.Success) Then
        GoTo somethingBadHappenedButNotAnException
    End If

    ''//Performs validation then saves it to the database
    ''//using the current transaction
    result = SaveOrganziation(dbOrg, organization)
    If (Not result.Success) Then GoTo somethingBadHappenedButNotAnException

somethingBadHappenedButNotAnException:
    _Repository.Transaction.Commit()
    _Repository.Connection.Close()
    Return result
End Sub

这是GoTo声明的正确使用,还是真的糟糕的设计?有更优雅的解决方案吗?希望这个样本能够得到重点



1> Joel Coehoor..:

如果你不得不问,不要这样做.

对于您的特定代码,您可以这样做:

Public Function SaveOrganization(ByVal organization As rv_o_Organization) As Result
    Dim result As Result = Result.Empty

    _Repository.Connection.Open()
    _Repository.Transaction = _Repository.Connection.BeginTransaction()

    'Performs validation then saves it to the database 
    'using the current transaction
    result = SaveMasterOrganization(organization.MasterOrganization)

    'Performs validation then saves it to the database 
    'using the current transaction
    If result.Success Then result = SaveOrganziation(dbOrg, organization)

    _Repository.Transaction.Commit()
    _Repository.Connection.Close()
    Return result
End Sub



2> Jason Punyon..:

真的很糟糕的设计.是.



3> Jon B..:

Goto声名狼借,它会让其他开发人员立刻认为你的代码很糟糕.即使你可以证明使用goto是最好的设计选择 - 你必须一次又一次地向任何看到你代码的人解释它.

为了你自己的声誉,就是不要这样做.

推荐阅读
mobiledu2402851373
这个屌丝很懒,什么也没留下!
DevBox开发工具箱 | 专业的在线开发工具网站    京公网安备 11010802040832号  |  京ICP备19059560号-6
Copyright © 1998 - 2020 DevBox.CN. All Rights Reserved devBox.cn 开发工具箱 版权所有