262
LESSON 22 Preventing Bugs
OTHER ASSERTIONS
In addition to input assertions, a method can make other assertions as it performs calculations. A
method can use assertions to check intermediate results and to validate final results before returning
them. A program can even use assertions to validate the value it receives from another method.
Often these assertions cannot be as exact as those you can perform on inputs but you may still be
able to catch some really ludicrous values.
For example, suppose an order processing form lets the user enter items for purchase and then
calculates the total cost. You could use assertions to verify that the total cost is between $0.01
and $1 million. This is a pretty wide range so you are unlikely to catch any but the most egregious
errors, but you may catch a few.
Note that you should not test user input errors with assertions. An assertion interrupts the program
so you can try to find a bug. Your code should check for user input errors and handle them without
interrupting the program. Remember, when you make a release build,
Debug.Assert calls go away
so you cannot rely on them to help the user enter valid values.
One drawback to assertions is that it’s hard to make programmers use them. When you’re writing
code, it’s hard to convince yourself that the code could be wrong. After all, if you knew there was a
bug in the code, you’d fix it.
Assertions are like seat belts, airbags, and bicycle helmets. You don’t use them because you expect
to need them today; you use them just on the off chance that you’ll need them some day. Usually
your assertions will just sit there doing nothing but if a bug does rear its ugly head a good set of
assertions can make the difference between finding the bug in seconds, hours, or days.
TRY IT
In this Try It, you write a method to calculate a department’s
average salary. The interesting part is adding assertions to
make sure the method is being called correctly.
To test the method, you’ll build the program shown in Figure 22-2.
The focus of this Try It is on the method that calculates the average,
not on the user interface. The assumption is that some other part
of a larger program would call this method, so the user interface
shown in Figure 22-2 is purely for testing purposes. A real program
would not allow the user to enter invalid values.
You can download the code and resources for this Try It from the book’s web
page at
www.wrox.com or www.CSharpHelper.com/24hour.html. You can find
them in the Lesson22 folder in the download.
FIGURE 222
596906c22.indd 262 4/7/10 12:33:38 PM