I have process that needs to create a bunch of records in the database and roll everything back if anything goes wrong. What I want to do is this:
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
Is this an ok use of the GoTo statement, or just really bad design? Is there a more elegant solution? Hopefully this sample is able to get the point across
If you have to ask, don’t do it.
For your specific code, you could do it like this: