Asserting Your Beliefs

"the programmer should make a number of definite assertions which can be checked individually, and from which the correctness of the whole program follows" 

- Alan Turin

In programming we often make assumptions.  Unfortunately our assumptions are not always correct, particularly during the process of software development when the nature of our code logic is evolving.

A standard technique used by software developers is the use of an Assert function that makes explicit the assumptions.  If the assumptions are invalid an error is raised.

I am writing some code today and I have two lists.  I am combining the elements of the two lists into an associative array.  The logic for the code only makes sense if the two lists are the same size.  Based on my data this condition should always be true.  But “should” is not the same as “is”.  If the condition is not true then I need to know about it immediately.

Here is an example of my code:

 Assert(NItems(lstTests)==NItems(lstDates),
     "mismatch between list items"
 );
 For (i=1,i<=NItems(lstTests),i++,
     testName = lstTests[i];
     dates = lstDates[i];
     arrDates[testName] = dates;
 );

If the number of items in the two lists do not match the following message is displayed:

assert-failure

No one likes to see error messages.  So if they are going to occur at least make them fun!

It would also be possible to enhance the window contents, for example, by including a link that would allow an email to be sent, or to create some diagnostic output in the log window.

Here is the code for the assert function:

assert-function

Why not just use conditional logic instead of the Assert function?  If I use an “if-then-else” structure in my code it implies that two conditions are possible (“if” or “else”).  Whilst both these conditions are possible one of the conditions only occurs if I have made a mistake in my logic.  My code is only as good as my assumptions and the Assert function makes these assumptions explicit.

Share the joy:
facebooktwittergoogle_pluslinkedinmailfacebooktwittergoogle_pluslinkedinmail

3 thoughts on “Asserting Your Beliefs”

Leave a Reply