Home
Do you do your validation with Exit Sub?
  v1.0 Posted at 26/04/2018 9:07 AM by Tiago Araujo

The Exit Sub statement can be very useful when used for validation filtering.
Instead of a deep nested If, use Exit Sub or Return to provide a short execution path for conditions which are invalid.

Private Sub AssignRightToLeft()
'Validate Right
If lstParaRight.SelectedIndex >= 0 Then
'Validate Left
If lstParaLeft.SelectedIndex >= 0 Then
Dim paraID As String = lstParaRight.SelectedValue.ToString
Dim mParagraph As BusinessLayer.Paragraph = New Paragraph
mParagraph.MoveRight(paraID)
RefreshData()
End If
End If
End Sub 

Figure: Bad example - using nested if for validation


Private Sub AssignRightToLeft()
'Validate Right and Left
If lstParaRight.SelectedIndex = -1 Then Return
If lstParaLeft.SelectedIndex = -1 Then Return
Dim paraID As String = lstParaRight.SelectedValue.ToString
Dim mParagraph As BusinessLayer.Paragraph = New Paragraph
mParagraph.MoveRight(paraID)
RefreshData()
End If
End If
End Sub

Figure: Good example - using Exit Sub to exit early if invalid ​

Related rules

    Do you feel this rule needs an update?

    If you want to be notified when this rule is updated, please enter your email address:

    Comments:

    Note: Social Media login for Yotpo is not working in IE or Safari, please use Chrome. We are waiting for Yotpo to fix it.