When should you assert?

Once you start using assertions seriously in your code, you need to be aware of some pertinent issues. The first and most important of these is when you should assert. The golden rule is that assertions should not take the place of either defensive programming or data validation. An assertion is normally used only to detect an illegal condition that should never happen if your program is working correctly. To return to the control software of our space shuttle, consider this code:

Sub InsertIntoEngine(ByVal vntiAnObject As Variant)

Debug.Assert TypeName(vntiAnObject) = Object
' The insert into engine code goes here.

End Sub

Asserting procedure arguments like this is fine, but only provided the assertion is in addition to some proper argument validation that handles nasty situations, such as trying to insert a nonobject into the engine. In other words, don’t ever let assertions take the place of normal validation as we did in this example. Instead you might want to say something like this:

Sub InsertIntoEngine(ByVal vntiAnObject As Variant)

If TypeName(vntiAnObject) <> "Object" Then
    Debug.Assert TypeName(vntiAnObject) = "Object"
    Err.Raise vbObjectError + mgInvalidObjectError
Else
    ' The insert into engine code goes here.
End If

End Sub

If the InsertIntoEngine routine was on a critical path and you weren’t allowed to generate any errors, you could avoid an engine accident by coding defensively instead:

Sub InsertIntoEngine(ByVal vntiAnObject As Variant)

If TypeName(vntiAnObject) <> "Object" Then
    Debug.Assert TypeName(vntiAnObject) = "Object"
    Exit Sub
Else
    ' The insert into engine code goes here.
End If

End Sub

Be aware that defensive programming like the above is dangerous if you don’t include the assertion statement. Although using defensive programming to write what might be called nonstop code is important for the prevention of user data loss as a result of program crashes, it can also have the unfortunate side effect of hiding bugs. Without the assertion statement, a programmer who called the InsertIntoEngine routine with an incorrect argument would not necessarily receive any warning of a problem. Whenever you find yourself programming defensively, include an assertion statement.