Team LiB
Previous Section Next Section

Don't Assert Legal Cases

But it's important to make sure every assert you write is truly a case that should never happen. Some developers write asserts for unusual but legitimate cases that do occasionally happen in a "normal" run of the program. That's a bad habit to get into, though. For example, suppose your online store presents a textbox where customers can type the name of a product, and then you have a function that looks up the price of that product:

using System.Collections;
using System.Diagnostics;
class PriceLookupClass {
    Hashtable pricesTable = ...;
    string GetPrice(string productName) {
        string price = (string)pricesTable[productName];
        if (price == null)
            Debug.Assert(false, "Error: Product not found");
        return price;

The problem here is that it's perfectly legal for a customer to type the name of a product your store doesn't carry. It's not a bug you need to fix. You definitely need to handle that case by displaying some kind of "Sorry, we don't carry that product" message, but a failed lookup in the hashtable is not a bug. Remove that assert immediately. Anytime you see an assert pop up, you ought to think, "Uh oh, some- thing's wrong and I need to figure out what!" But if you allow yourself to start thinking, "Oh, that assert doesn't really mean anything," then you'll never have the motivation to fix the problems indicated by asserts again.

On the other hand, suppose you didn't offer the user a textbox and instead forced her to choose from a drop-down list of products that you know your store carries. Would an assert be appropriate then? Yes! With a drop-down list, it would be impossible for the user to choose a product you don't carry—so if the hashtable lookup failed then, it would mean you really did have a bug. If that's what your GUI looks like, then leave the assert in this function. Notice the implication of that statement. You can't base your asserts just on the surrounding code; you have to use "big picture" logic to understand which circumstances are possible and which aren't.

Anytime you see an assert pop up, you need to either fix it or remove it— leaving it untouched is a sin. But make sure you think twice before you remove the assert. Removing it is sometimes the right thing to do, but first make certain you understand the original purpose of the assert and why it is no longer valid. Don't give in to the temptation to remove an assert just because you don't understand why it's failing and things seem to work if you ignore it. The person who wrote the code had a reason for believing that condition would always be true, so make sure you understand it before removing the assert.

Team LiB
Previous Section Next Section