On Assertions

The proper use of assertions is one of the hallmarks of a professional programmer.

Our confirmation bias as creators makes it hard to test our work properly. We tend to write tests to prove the code works, rather than trying to prove it doesn’t. There are many reasons for this. We pretend to ourselves and others that we can be (could be) perfect, when in fact we consistently make mistakes. Bugs in code are seen as “bad” rather than “inevitable,” so psychologically we want to see fewer of them, not uncover more of them. “He writes perfect code” is seen as a compliment, rather than a euphemism for “He never takes risks, so his code is as boring and heavily used as cold spaghetti.”

Some cultures teach us to aspire to perfection, and punish mistakes, in education and work, which makes this attitude worse. To accept that we’re fallible, and then to learn how to turn that into profit rather than shame, is one of the hardest intellectual exercises in any profession. We leverage our fallibilities by working with others, and by challenging our own work sooner, not later.

One trick that makes it easier is to use assertions. Assertions are not a form of error handling. They are executable theories of fact. The code asserts, “At this point, such and such must be true,” and if the assertion fails, the code kills itself.

The faster you can prove code incorrect, the faster and more accurately you can fix it. Believing that code works and proving that it behaves ...

Get ZeroMQ now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.