I remember there was an "and_then" operator in VAX-Pascal. I miss it in Delphi-Pascal. What is the best way to do a safe check in Delphi?
From https://www.gnu-pascal.de/gpc/and_005fthen.html:
“The and_then short-circuit logical operator performs the same operation as the logical operator and. But while the ISO standard does not specify anything about the evaluation of the operands of and – they may be evaluated in any order, or not at all – and_then has a well-defined behaviour: It evaluates the first operand. If the result is False, and_then returns False without evaluating the second operand. If it is True, the second operand is evaluated and returned.”
As an example I have a StringList and want to check if first element has the value 'ID'. And of course I can only check first element if the list is not empty. The long and safe way:
xlst := TStringList.Create;
if (xlst.Count > 0) then
begin
if (xlst[0] = 'ID') then ShowMessage(xlst[0])
end
else ShowMessage('String list is empty');
Is there a shorter way to do?
Test 1:
xlst := TStringList.Create;
if (xlst.Count > 0) and (xlst[0] := 'ID') then ShowMessage(xlst[0])
else ShowMessage('String list is empty');
It works but is it safe? Is the second test only executed if the first is true? Can I rely on that the order of execution is the order written in the code?
Test 2:
xlst := TStringList.Create;
if (xlst[0] = 'ID') and (xlst.Count > 0) then ShowMessage(xlst[0])
else ShowMessage('String list is empty');
As expected this code will lead to an error at runtime.
{$B-} {$BOOLEVAL OFF}
is default.{$B-}
. The cure is to always testCount
first as you do in Test1. It is safe in the default{$B-}
state.