Demystifying assertions

Recently, I spent a fair bit of time explaining assertions to an apprentice on my team. While he could understand how assertions work, he struggled to grasp the motives for using them.

Indeed, it is arguable that defensive coding in the form of guard conditions and exception handling makes assertions redundant. But there is a dichotomy of assertions and defensive coding, which I can best summarise in this way:

Assertions protect the programmer. Defensive coding protects the user.

Let’s review what assertions are and how they should be used—

What are assertions used for? Assertions are used to state conditions that the programmer holds to be true at specific points of their program.

How do assertions work? The programmer writes assertions by using the language’s or framework’s features to add code that causes their program to crash if the desired conditions are not satisfied. Either a compiler – or a runtime, depending on programming language or framework – throws an error whenever it encounters a failed assertion.

Why are assertions important? Assertions are important because they help the programmer spot logical errors in their program whilst they are iteratively writing and testing their code. They also facilitate debugging.

When are assertions used? Assertions are used whenever the programmer writes code for which they want guarantee that it matches their intent.

When are assertions NOT used? Assertions are not used when the programmer needs to validate inputs and arguments that are passed to the program or to parts of the program. (In those cases, the programmer should use defensive coding or should allow the program to crash if the inputs are being passed in an unwarranted way, such as an exploit attack.)

Leave a comment

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.