Using Assert()
Volume Number: 13
Issue Number: 12
Column Tag: Beginner's Corner
by Peter N. Lewis, Perth, Australia
Understanding assertions and how and when to use them
Many programmers believe it is impossible to write bug free code. They just assume
bugs are a part of life and that beta testers and QA departments (or even end users!)
will find and report the bugs which will then (hopefully) be tracked down and
resolved. I'm not sure I believe it is possible to write bug free code, but one thing I
certainly believe is that it will not happen without a conscious effort on the part of the
programmer.
Once you have decided that writing bug free code is a worthwhile goal, the first and
most important tool at your disposal is the "Assertion". An assertion is simply a piece
of code that validates part of the state of your program, and alerts you if something is
wrong. This article describes assertions, why you want to use them, what they are,
when and where to use them, and how you implement them. Throughout this article I
will use examples in Pascal or C, but the concepts apply to almost any language.
Why You Should Use Assertions
Bugs come in many shapes and sizes, but there is a general rule of thumb that the
earlier you detect a bug the less time it takes to fix it: