Using Assertions

Assertions let you check whether an application is behaving as you expect at a particular point. The following example shows you how to use an assertion in your code:

' Assertions need the System.Diagnostics namespace Imports System.Diagnostics

Module Modulel

Sub Main() ' Call the function Test(-l) End Sub

' A test function

Public Sub Test(ByVal n As Integer) Trace.Assert(n > 0, "Argument is not positive") ' more code... End Sub End Module

The program starts by importing the System.Diagnostics namespace: The assertion facility is part of this namespace, so you'll save yourself a lot of typing by importing the namespace at the beginning of your program.

The function Test() takes an integer as an argument, and it should probably never be called with an argument that is less than or equal to zero. If I'm sure of this, I put a call to Trace.Assert() in to check the value of the argument. Note

Assert() takes two arguments: The first is an expression that evaluates to True or False, whereas the second is a message that is printed in the event of failure. Assert() checks the condition: If it is True—in this case, if n is greater than zero—no action is taken. If it is False, an error dialog is displayed, which is similar to the one shown in Figure 12.5.

Note

There are two other overloads of Assert(): the first, with one argument, simply checks a condition and prints a standard message. The second takes three arguments—the condition, a brief message, and a detailed message.

The idea is that you scatter assertions throughout your code as you write it, and these assertions mark invariant conditions—that is, conditions that must be True all the time. If at some point something happens to change the behavior of the program (such as changes in the code or data) and it causes an assertion to fail, you'll find out about it.

There are two versions of Assert(), both are shared methods. The version belonging to the Debug class is only active in debug builds and is disabled in release builds, whereas the version in the Trace class is active in all builds. Which one you choose depends on whether you want your assertions to be active all the time or not.

There is also a shared Fail() method, which is similar to Assert() but doesn't have an expression to evaluate. Whenever Fail() is executed, it displays the assertion dialog with an error message, so you use it to mark places in the code that should never be reached.

0 0

Post a comment