Kelsey> Nor did I say it was; I said that if you have error-handling
Kelsey> code, assert becomes instantly useless and if you lack
Kelsey> error-handling code, your *app* becomes instantly useless;
Kelsey> thus in no case does having assert offer you anything useful.
This claim is simply untrue.
Assertions are important for detecting conditions that, in an ideal
world, would be incapable of happening. Such conditions are often due
to bugs elsewhere in the code, which implies that no meaningful error
recovery is possible. After all, what reason is there to believe that
any attempt at recovery would not contain similar bugs?
A variation on this idea is when the validity checking is too
expensive to do during production, which makes it important to be able
to turn it on only during testing.
In circumstances such as these, the most sensible thing the program
can do when it discovers the ``impossible'' situation is to halt
instantly, and preserve as much information as possible about the
state of the program at the time the problem was discovered.
Here are three examples:
1) A memory allocator that discovers that the internal data structures
that it uses to keep track of what memory is allocated have become
corrupted. At this point, it is no longer possible to tell what
memory is allocated and what isn't. Any attempt at recovery is
likely only to obscure the problem further.
2) A container class that uses a balanced binary tree as its
implementation. Every node of such a tree is required to meet certain
balance criteria. The code that deals with the tree is designed to
maintain the balance criteria at all times. If the program ever
discovers that the tree fails to meet the balance criteria, it means
that something is seriously broken -- and again, no recovery is
possible.
3) A program that maintains a table that is kept sorted. Values
are frequently sought in the table by binary search, which is why
keeping the table sorted is important. Every once in a while, a
value is inserted into the table, which is a logical time to verify
that the table is still sorted. It makes no sense to verify that
the table is sorted every time you search for an element, because
then there is no point in using binary searches at all.
Suppose you find that the table has somehow become unsorted. Then it
is useful as a debugging tool to be able to check the table's order
every time you search it. Again, the object of the game is to be able
to stop the program as soon as possible after the problem has been
discovered, and again no meaningful recovery is possible.
In all of these cases, there is a category of error beyond merely
passing an argument to a function that is outside the function's
domain. It is to forestall such problems that assertions are useful.
--
Andrew Koenig, a...@research.att.com, http://www.research.att.com/info/ark