Exiting from Procedures


One of the rules of structured programming is: a procedure should have one and only one exit. Some members of the coding police criticized the code in the first edition of Hardcore Visual Basic for violating this rule. I plead guilty.


I respect this rule. I honor the intention of encouraging disciplined code with carefully structured exits. I admire programmers who follow the rule without twisting code into contortions. But after careful thought, I have chosen not to follow it myself. If you make a different choice, that’s fine with me.


My justification, pitiful as it might seem to purists, is that multiple exits can make code shorter and, to my eye, more natural. You can always get just one exit, but you might have to introduce Gotos or extra levels of indentation to do it. Exit Sub and Exit Function work for me. Take the Among function, which gives Visual Basic something comparable to one of my favorite Pascal features, the in operator. Here’s how I wrote it:

‘ Pascal:    if ch in [‘a’, ‘f’, ‘g’] then
‘ Basic: If Among(ch, “a”, “f”, “g”) Then
Function Among(vTarget As Variant, _
ParamArray a() As Variant) As Boolean
Among = True ‘ Assume found
Dim v As Variant
For Each v In a()
If v = vTarget Then Exit Function
Next
Among = False
End Function

This code can exit from the middle of the loop if a match is found or from the end of the function if a match is not found. Is that really less structured, more prone to errors, or less readable than this kosher version?

Function Among(vTarget As Variant, _
ParamArray a() As Variant) As Boolean
‘ Among = False ‘ Assume not found
Dim v As Variant
For Each v In a()
If v = vTarget Then
Among = True
Exit For
End If
Next
End Function

Decide for yourself how strictly you want to follow this rule, but get off my case.