October 11, 2006
Much ado about nothing
Have you ever noticed how important it is to make programs do the right thing when their input is empty? And how it's not always easy to know for sure what the right thing is?
Here's a simple example: Suppose you're writing a program that computes the sum of all of the elements in a sequence. What should it do when there aren't any elements?
A little reflection may convince you that the sum of an empty sequence is zero. But why? Why, for example, wouldn't it be equally correct to throw an exception?
The answer to the question hinges on whether the program's behavior on an empty sequence makes conceptual sense, or whether it is just a convenience. I claim that it makes conceptual sense to say that the sum of an empty sequence is zero. The reason is that if you remove one element from a nonempty sequence, sum the rest of the elements, and then add the element you removed, you get the sum of all of the elements.
In other words, sum(s[0]...s[n]) is equal to sum(s[0]...s[n-1])+s[n] whenever n>1. By defining the sum of an empty sequence to be zero, we preserve this property when n=1 (Of course, we can't preserve the property when n=0, because doing so would require us to ascribe a value to v[-1]).
Because defining the sum as zero preserves this property, we can be confident that the definition is consistent with the rest of the program's behavior.
To confirm that you get the point, you might think about how to define the product of the elements of an empty sequence.
Posted by Andrew Koenig at 06:23 PM Permalink
|