Delphi coding hints and tips.
Assertions
Assert is a standard procedure that evaluates a boolean expression, if false a EAssertionFailed exception will be raised. They are used as a testing and debugging aid such that you can intercept unexpected conditions. Within the project options dialog there is a compiler option 'Assertion (C)' which allows you to optionally compile in all Assert calls. You can also use the following compiler directives do switch assertions off or on through your code:-
$ASSERTIONS ON, $ASSERTIONS OFF or $C+, $C-
Heres an example of how you could use a assertion. Below is a simple function which given a integer 0 to 9 will return the string for the digit.
function TForm1.DigitToStr(No:Integer):string;
const
NoStr:array[0..9]of string=(
'Zero','One','Two','Three','Four',
'Five','Six','Seven','Eight','Nine');
begin
Assert((No>=0)and(No<=9));
if (No>=0)and(No<=9)
then
Result:=NoStr[No]
else
Result:='Error!' ;
end;
The assertion is used to test the No passed to the function is in the range of 0 to 9. So when testing the application if a value of say 11 is passed to the function an EAssertionFailed exception will be raised and you become aware of the error. Note I have still checked the No range with a conventional if then and return an error when out of range. This is so when I delivery this application I would compile without assertions and the function when not fall over but return an error.
Think of assertions as a sanity check. Also note the EAssertionFailed exception will give you the full path a file name of the source and the line number within the source where the assertion failed - very useful!
Do not use assertion other than their intended purpose, i.e. to control the flow of execution within the program by getting assert to raise an exception. Once the assertion compiler option is off your flow logical will not be compiled.


