Recently, I explained assertions to an apprentice. Although he could understand how they work, he struggled to find uses for them.

It’s arguable that defensive coding in the form of guard conditions and exception handling makes assertions redundant. But there’s a real dichotomy in assertive coding and defensive coding that can be summarised like this:

Assertions protect the programmer. Defensive coding protects the program.

Let’s review what assertions are and how they are used.

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

How do assertions work? The programmer writes a function call that checks for certain conditions and stops the program execution if they are not present. Typically, assertions are a feature built in the programming language or a framework. For example, the C standard library provides the assert() function. The compiler or the runtime halts when it encounters a failed assertion.

Why are assertions important? Assertions are important because they help the programmer find logical errors in their program during development. They are a useful tool for debugging.

When are assertions used? Assertions are used whenever the programmer wants to check that their code meets expectations.

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 Reply

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