Microsoft Office 2000/Visual Basic Programmer's Guide |
You can use conditional compilation to selectively include blocks of debugging code by testing for the value of a conditional compilation constant. If the constant is True, the debugging code is included. To do this, you specify a conditional compilation constant by using the #Const directive. You then test for the value of this constant within a procedure by using the #If…Then…#Else directive within a procedure. For example, the following procedure uses the value of the FLAG_DEBUG conditional compilation constant to determine if the conditional constant is set to True. If the constant is set to True, the Assert method of the Debug object is used to test the validity of the procedure's input parameters. For example:
Sub OutputString(strMessage As String, _
Optional intOutputType As Integer = 0)
Dim intFileNum As Integer
#If FLAG_DEBUG = True Then
' Test validity of strMessage.
Debug.Assert Len(strMessage) > 0
' Test validity of intOutputType.
Debug.Assert intOutputType >= 0 and intOutputType <= 3
Stop
#End If
Select Case intOutputType
Case 0
.
.
.
End Sub
The OutputString procedure is available in the modErrorCode module in ErrorHandlers.dot in the ODETools\V9\Samples\OPG\Samples\CH08 subfolder on the Office 2000 Developer CD-ROM.
For more information about using the Assert method of the Debug object, see the next section, "Using Assertions."
Using conditional compilation is really a shortcut for commenting out entire blocks of code depending on a global setting. Without the ability to use the constant as a flag to direct program flow, you would have to litter your code with commented-out calls to alternative procedures. If you always use conditional compilation constants to test alternative procedures, then you have an easy way to turn on and off calls to the designated procedures and an easy way to find the code that you ultimately decide to remove. The cost of using this technique is that you must give a great deal of thought to how your code is constructed and called. Although this may mean a little more work, it results in the kind of manageable, maintainable, and reusable code that is discussed in Chapter 3, "Writing Solid Code."