What to Assert


Asserting is an art form. Languages have been specifically designed—Eiffel comes to mind—to encourage it. Books have been written about it. Steve Maguire’s Writing Solid Code (Microsoft Press, 1993) is an excellent book on asserting and other debugging topics, although you’ll have to translate from C to Basic as you read it. I can only touch on the subject here, but you’ll see examples throughout the sample code.


The most important thing to know about debugging code is when to assert and when to validate. Validating means checking the input at run time and taking
appropriate action. If you ask the user for a number between 1 and 10, you have to recognize when the user enters 11 and ask again politely (or handle 11 anyway, or round down to 10, or delete everything on the idiot’s hard disk, or whatever). But you can’t assert.


Here’s an example. Lots of Windows API functions return error values, but errors don’t always mean the same thing. A common Windows sequence (as you’ll see in future chapters) is to create, use, and delete. It works like this:

hSomething = CreateSomething(x, y, clr, AND_SO_ON)
‘ Do something with hSomething
f = DeleteSomething(hSomething)

In this case, CreateSomething either returns a handle to a Something or returns a 0 handle (the constant hNull) indicating failure. DeleteSomething returns True or False, depending on whether you can delete the object.


If you get hNull back from CreateSomething, it’s not your fault. There’s probably not enough memory, or Windows has used up all the Somethings. It’s your responsibility to politely tell the user to choose some other action. If Delete­Something fails, however, it probably is your fault. You passed hSomething to the wrong procedure, or you traded an hSomething for an hAnything and forgot to swap it back. For whatever reason, the hSomething variable no longer contains a Something handle. There’s no point telling the user. What could you say? You must do some soul-searching to fix the bug. But an assertion such as this one catches the mistake:

hSomething = CreateSomething(x, y, clr, AND_SO_ON)
If hSomething = hNull Then
BackWayOut
Exit Sub
End If
‘ Do something with Something
f = DeleteSomething(hSomething)
BugAssert f

WARNING Resist the temptation to combine assertions with other statements. The line

BugAssert DeleteSomething(hSomething)

seems to work, but if you replace BugAssert with ‘ BugAssert, you’ll get an unpleasant surprise when DeleteSomething disappears along with the assertion.


Incidentally, if you notice more assertions in the examples in early chapters of this book than in late ones, well…that’s no excuse for you. Never let tight deadlines compromise your efforts to write correct code. It takes longer to debug than to write it right the first time.