Visual Basic

Tip 7: Use assertions.

I've already briefed you on some stuff about assertions; here's the full scoop.

Assertions are routines (in Visual Basic) that use expressions to assert that something is or is not True. For example, you might have a line of code like this in your project:

    nFile = FreeFile

So how do you know if it works? Maybe you think that it raises an exception if all your file handles are taken up. (The Help file doesn't tell you.) We wouldn't leave this to chance. What we'd do during both unit and system testing is use assertions to check our assumption that all is indeed well. We would have a line that looks like this following the line above:

    Call Assert(nFile <> 0, "FreeFile")

This checks that nFile is not set to 0. Assertions are easy to use and extremely handy. They would be even better if Visual Basic had a "stringizing" preprocessor like the one that comes with most C compilers. Then it could fill in the second parameter for you with the asserted expression, like this:

    Call Assert(nFile <> 0, "nFile <> 0")

Assertions should be removed at run time. They serve only for testing during development, a kind of soft error handler, if you will. (This removal could be done using the App.InDesign property described earlier.) If an assertion regularly fails during development, we usually place a real test around it; that is, we test for it specifically in code. For the preceding example, we would replace

    Call Assert(nFile <> 0, "FreeFile")

with

If nFile = 0 Then
      Err.Raise ????
  End If

If an assertion doesn't fail regularly (or at all) during development, we remove the assertion.

If you're asking yourself, "Why isn't he using Debug.Assert?" you need to go back and read all of Tip 6.

Tip 8: Don't retrofit blind error handlers.

The best error handlers are written when the routine they protect is being written. Tools that insert error handlers for you help but are not the answer. These tools can be used to retrofit semi-intelligent error handlers into your code once you're through writing-but is this a good idea? Your application will be error handler-enabled, that's for sure; but how dynamic will it be in its handling of any errors? Not very!

We rarely use any kind of tool for this purpose because in fitting a blind error handler there is little chance of adding any code that could recover from a given error situation. In other words, by fitting an error handler after the fact, you might just as well put this line of pseudocode in each routine:

On Error Condition Report Error

You're handling errors but in a blind, automated fashion. No recovery is possible here. In a nutshell, a blind error handler is potentially of little real use, although it is of course better than having no error handling at all. Think "exception" as you write the code and use automation tools only to provide a template from which to work.