Tips and Tricks – When to ASSERT or not ASSERT …

that is the question.  The use of assertions often confuses even the most experienced developers.  Developers should be considering whether the expression they are going to ASSERT is a potential bug condition or whether it is an attempt to trap an error.  An error in this case would be a run-time condition that should be handled by the software.  Assertions are assumptions about the state of the system at a given point in time that if incorrect means there is a bug in the software.

Take for example the following code snippet and declarations:

201508A2F1

In the above code snippet, the allowed system states are defined within an enumeration.  A function, System_StateSet, is used by application code to set the system state.  The function as it is currently written doesn’t perform any checks on the input or output of the function which are prime candidates for the use of assertions.  Remember, an assertion should be used to find bugs in the code NOT trap error conditions.  Passing anything other than a SystemState_t to System_StateSet is not an error but a BUG!  The BUG should be fixed.  With this in mind, System_StateSet can be rewritten as follows:

201508A2F2

During development if a bug exists in the code that allows SystemState to exceed SYSTEM_MAX_STATE, the assertion will catch it.  The use of assertions in this way is completely appropriate especially if setting the system state is controlled by application code and NOT user input.  User input falls within the runtime error category and should be error trapped not asserted.

Let’s now considered another brief example where an assertion would not be appropriate.  Examine the following code snippet:

201508A2F3

In the above example, a file is being opened in read-only mode.  The FileHandle symbol should be non-zero if the file is opened successfully.  The assertion is being used to make sure that the FileHandle is non-zero, otherwise the assertion will fire.  The problem is that whether the file Test.txt exists on the file system is most likely completely user related.  Rather than firing an assertion if the file doesn’t exist or can’t be opened, it would be more appropriate to handle this in a run-time error trapping fashion.

The best definition for an assertion (that I have been able to find) is “An assertion is a Boolean expression at a specific point in a program that will be true unless there is a bug in the program.”  Memorize this definition and let it be the guide as to whether it is appropriate to use an assertion or a run-time error trap.

Share >

Leave a Reply

Your email address will not be published. Required fields are marked *

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