Reputation: 6271
Is there any better way of handling nested else if statements that have different outcomes?
Here is an example of one of my nested statements to explain:
If My.Computer.Network.Ping(computerName) = True Then
Call InstallVS(computerName)
If My.Computer.Network.Ping(computerName) = True Then
Call PEC(computerName)
If My.Computer.Network.Ping(computerName) = True Then
Call RemoveSoftware(computerName)
Else
Call WriteLog(computerName & " lost connectivity while attemping to remove the temp software")
End If
Else
Call WriteLog(computerName & " lost connectivity while Forcing Communication")
End If
Else
Call WriteLog(computerName & " lost connectivity while attemping to Install")
End If
I have a requirement to lots of these type of statements, some are smaller, some are a lot larger.
Upvotes: 1
Views: 2004
Reputation: 14700
You can create a method called PingOrFail
, which will test connectivity or throw an exception otherwise, with a given error message. Then your code flow could look something like this:
Try
PingOrFail(computerName, "attempting to install")
Call InstallVS(computerName)
PingOrFail(computerName, "forcing communications")
Call PEC(computerName)
PingOrFail(computerName, "removing temp software")
RemoveSoftware(computerName)
Catch ex As Exception
Call WriteLog (computerName & " lost connectivity while " & ex.Message)
End Try
And this is the PingOrFail method:
Public Sub PingOrFail(computerName as String, message As String)
If My.Computer.Network.Ping(computerName) = False
Throw New Exception (message)
End If
End Sub
Upvotes: 3
Reputation: 4007
These statements don't need to be nested, they could just raise exceptions if they fail.
Private Sub DoStuff(ByVal computerName As String)
Try
If My.Computer.Network.Ping(computerName) Then
InstallVS(computerName)
Else
Throw New Exception(computerName & " lost connectivity while attemping to Install")
End If
If My.Computer.Network.Ping(computerName) Then
PEC(computerName)
Else
Throw New Exception(computerName & " lost connectivity while Forcing Communication")
End If
If My.Computer.Network.Ping(computerName) Then
RemoveSoftware(computerName)
Else
Throw New Exception(computerName & " lost connectivity while attemping to remove the temp software")
End If
Catch ex As Exception
WriteLog(ex.Message)
End Try
End Sub
Upvotes: 2