我有进程需要在数据库中创建一堆记录,如果出现任何问题,请将所有内容回滚.我想要做的是:
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声明的正确使用,还是真的糟糕的设计?有更优雅的解决方案吗?希望这个样本能够得到重点
如果你不得不问,不要这样做.
对于您的特定代码,您可以这样做:
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
真的很糟糕的设计.是.
Goto声名狼借,它会让其他开发人员立刻认为你的代码很糟糕.即使你可以证明使用goto是最好的设计选择 - 你必须一次又一次地向任何看到你代码的人解释它.
为了你自己的声誉,就是不要这样做.