You can use IF (and importantly Else) to make certain sections of code execute/not execute. Or you can simply return from the function (or exit sub).
Which do you prefer / why?
ex. A
Code:
Dim _searchText As String = txtSearch.Text.Trim()
If _searchText = "" Then
MessageBox.Show("Please enter *******")
txtSearch.Focus()
Else
''start to process the user input
End If
ex. B
Code:
Dim _searchText As String = txtSearch.Text.Trim()
If _searchText = "" Then
MessageBox.Show("Please enter ******")
txtSearch.Focus()
Exit Sub
End If
''only runs code below this line if the above IF-block wasn't executed.
''start to process the user input
I tend to use the 2nd because it's 1 line shorter/the logic seems fine. The "Else" is implied, but the first seems "more clear".?
I've seen a lot of code that simply returns/exits instead of having an else clause. Maybe to avoid too much nesting?
I like to see all the "fail cases" checked at the top, then only continue if all checks were good. Else statements do pretty much the same thing, but the code is sectioned a little differently - with the 'error' cases being scattered through the function(each else blocks), instead of the top of the function.