How do you use assertions?

Barry Lapthorn joins the debate about assertions and how they should be used.

His first point is that the traditional "C++" style of implementing an assertion with the use of a focus-grabbing process-interrupting modal dialog box simply doesn't work in production systems. No argument here, and no argument from Len.

Barry's second argument is that you should be able to replace many asssertions with a unit test. I'm not convinced by this at all. An assertion implements a test where you don't know what to do in the event of failure. It tests for a condition that should never happen in production. There's a significant opportunity cost associated with coding and testing unit tests, which means that they're not necessarily what you want to implement for conditions that, in reality, should never happen.

Barry's final point is that many assertions should be replaced by defensive programming. See my original post for where I think you should you use assertions and where you should use defensive programming. I would add that a properly-implemented assertion logs the stack trace, local variables/parameters, and other important information at the point of failure, before any associated exception or other defensive programming has had a chance to destroy the incriminating evidence. And once again, is defensive programming the best choice for a situation where you have no idea what to do? In the face of an assert-type situation, you're basically SOL and all you can do is to try to rollback properly, possibly by throwing an AssertionException in addition to doing the assert.

Finally, Barry says: "If it's a modern system, don't use them [assertions] at all." I'm not sure where to start with this rather unusual viewpoint. It flatly ignores a rich history associated with assertions. But you should make up your own mind about when and how to use them in your code.

UPDATED: Unlike both Len and Barry, I'm not a C/C++ guy. But Raymond Chen, the "best programmer in the world" according to Joel, has just posted a C++ snippet showing a good use of assert.