Assertions

Introduction

Assertions” (or simply “Asserts” are commonly used in many programming languages to help developers read and understand code, and to help to detect possible defects (bugs).

An assert is usually a predicate that tests a variable in the program and returns a boolean (true / false) value. In common English, it is like saying:

This <some expression> is true.

Although Nyquist does not have a specific Assert command, it is easy to achieve the same functionality.

Example in Pseudo Code

In Nyquist that would be written as:

To make it more obvious that the code is intending to assert the test condition, we could write an ASSERT function, include it in our code before use, then call the ASSERT function as and when needed.

which we could then use like this:

How it works

When we call the ASSERT function, we can pass between one and three arguments.

  • The first argument is required, and is the expression that we are asserting is True.
  • The second argument (optional) is the error message that is printed if our assertion is wrong [the expression evaluates to False].
  • The third argument (optional) is the variable that has been tested.

Looking at our ASSERT function, we see that the error message ‘msg’ defaults to an empty string, and the third argument ‘arg’ is NIL if not passed by the function call.

In our use example, ‘x’ is greater than 0 in the second line so the assertion is True and there is no error. Similarly, in the last line, ‘x’ is greater than 1, so again the assertion is True and there is no error. However, if we make a false assertion, then there will be an error printed to the Debug output:

Returns the error:

Debug Only?

It’s worth noting that if an Assert fails, it may not indicate a fatal error in the program. It may indicate that a value is not what the developer expected but is still OK, or it may indicate that a value is outside of the expected range but may still be acceptable. In most cases it is of no use to end users whether an Assert passes or fails – end users are interested in whether the code works, and really not interested in what is happening under the hood. Asserts are primarily for developers, and often we would only want them to run when debugging, not when running the code normally.

So how can we make an Assert run only when debugging?

Nyquist has a system variable *TRACENABLE* which evaluates to True when the plug-in Debug button is pressed, and False (NIL) when the plug-in is run with the normal ‘OK’ button [unless overridden in the code]. Thus we can modify our Assert function to run only when *tracenable* is True.

When running this code normally, it will print “8” and there will be no error [because *tracenable* is NIL], but when running with the Debug button we see the error:

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.