Saturday, February 28, 2004

Good Assertions example

I was just looking over some code I had written sometime back and came across something that I thought would be a good area to use Assertions.

This has to do with using enums. Enums in c/c++/c# (and coming soon to Java in 1.5) are types which consist of some named constants. They are much preferable to just constants or "magic" numbers cause they are much clearer and are categorized.

Anyway, here's a simple ex of using it...

enum Color
{
    Red,
    Blue,
    Green
}

If your method takes a Color argument it can work with the values set in this enum.

private void ChangeBackground( Color color )
{
    switch ( color )
    {
        case Color.Red:
            // Change background to red
            break;

        case Color.Blue:
            // Change background to blue
            break;

        case Color.Green:
            // Change background to green
            break;

        default:
        // Don't do anything
        break;
    }
}

This is fine, but what if sometime in the future someone adds a new value to Color? That switch statement will drop down to the default case. And you won't even notice it.

So it would be good practice to add an assertion in the default case.

default:
    Debug.Assert( false, "ChangeBackground(): Color " + color + " was not recognized" );

This is basically protecting yourself from your own code. In this example, it's not such a huge deal if it falls through to the default case... just that your newly added color won't be handled. But in other cases it might be more critical.

No comments: