Assert Yourself
Basic programmers have been too long deprived of one of the common tools of debugging—the assertion procedure. Assertion deals with the concept of proof. If you write a piece of code, how can you prove that it works? If it crashes, you’ve proved that it doesn’t work. But if it runs successfully, you’ve proved
only that it ran successfully this time, not that it will run next time, with differ-ent input.
The way to approach proof in programming is to rule out all invalid inputs, call the procedure, and then verify that its output is valid. Although you can’t always determine which inputs are invalid and you can’t always figure out a way to validate output, it’s nevertheless worth trying. You can often rule out many invalid inputs and at least partially validate output by using assertion procedures. An assertion procedure simply evaluates an expression, terminating the program with an appropriate message if the asserted expression is false.
For example, the following sub insists that users call it according to internal rules not enforced by the language:
Sub InsertChar(sTarget As String, sChar As String, iPos As Integer)
BugAssert Len(sChar) = 1 ‘ Accept characters only
BugAssert iPos > 0 ‘ Don’t insert before beginning
BugAssert iPos <= Len(sTarget) ‘ Don’t insert beyond end
Mid$(sTarget, iPos, 1) = sChar ‘ Do work
End Sub
The secret of successful assertion is to assert every possible condition that might go wrong. Of course, you won’t feel comfortable asserting aggressively if you know that each assertion increases the size and decreases the speed of your finished application. For that reason, assertion procedures are traditionally coded conditionally so that they exist during a debugging phase but disappear when the finished product is shipped.
Since Visual Basic’s conditional compilation features are significantly less powerful than those of most languages, version 5 tries to solve the assert problem by adding a built-in Assert method for the Debug object. Unfortunately, Debug.Assert doesn’t measure up to the needs of professional programmers. We’ll discuss it briefly but then move on to a real asserting and logging system based on conditional compilation.