One of the recurring themes in theCoders at Work book that I enjoyed recently, is that several of the expert practitioners interviewed in the book mentioned how useful they found thinking about code in terms of its invariants. The use of assertions does seem to lend itself to testing invariants like this – some quantity which can be calculated at the start of a function call, and then asserted to be unchanged by the end of it.
So can assertions be useful even in code that is well unit-tested?
Friday, November 27, 2009
I wanted to record this, because this is one place where I do not trust unit-tests, altogether. And I make use of "asserts" in production code.
In production code, I use asserts to test conditions that I cannot fathom how they could be violated, but that I cannot prove or unit-test that the condition cannot be violated, in any and all situations. I want the production code to “fail-fast” before beginning at the assert, because I know that if the condition IS violated, there is zero chance of the algorithm performing correctly. In these cases I am privately wishing for the assert to fail, because then I will have learned something very surprising.