An assertion is a statement in many programming languages such as C, C++, Java, etc., that enables you to test your assumptions about your program. For example, if you write a method that calculates the speed of a particle, you might assert that the calculated speed is less than the speed of light.
Each assertion contains a boolean expression that you believe will be true when the assertion executes. If it is not true, the system will throw an error. By verifying that the boolean expression is indeed true, the assertion confirms your assumptions about the behavior of your program, increasing your confidence that the program is free of errors.
Experience has shown that writing assertions while programming is one of the quickest and most effective ways to detect and correct bugs. As an added benefit, assertions serve to document the inner workings of your program, enhancing maintainability.
For more information on assertions see Assertion (Computing) on Wikipedia.
This Tech Tip explores a way to use assertions in 4D language and help you develop error free code faster.
In other languages, assertions (assert) is a language "macro". Language macros, such as "assert", exist in the source code then depending on a "pragma directive" at compilation time, the assertion code may or may not be compiled ito the executable. Those types to language extension, macros and pragma directives, are not a feature of the 4D language.
Given that, the "Assert" method below tests for whether or not the 4D application is compiled. If it is compiled the method simply returns true. The assumption of the method is that sufficient testing has been done in interpreted mode.
The Assert method simply takes a boolean expression and asserts its truth. If the expression is true, execution continues without any noticeable interruption. However, if the assertion is false, it halts code execution immediately by displaying an alert that displays the name of the affected method and the message that was stipulated in the third parameter. It also gives the opportunity to drop into the degugger by holding down the Shift key when dismissing the alert.
Use Assert as follows: Assert($Condition;$CallingMethod;$AlertMsg)
One example is shown here:
|If (Assert ($Divider>0;$MethodName_T;"Divide by zero condition!"))|
The Assert method follows:
If (Is compiled mode)
`If compiled the assumption is the calling method has already passed this test
If (Count parameters#3)
ALERT(Current method name+": Assert called with incorrect # of parameters (3).")