Is it possible to create an exit function in Delphi 2007?
I am using Delphi 2007 and wondering, perhaps, if not, then perhaps in a different version of Delphi.
My code at the moment looks like doo1
, but what I would like to have is something like doo3
.
I did doo2
and it works, but I would prefer with the function exitIfFalse
in one place and not as sub-procedures in many places.
function foo(const bar: Word): boolean;
begin
Result:= bar = 42;
end;
function doo1: integer;
begin
if not foo(42) then begin
Result:= 1;
exit;
end;
if not foo(8) then begin
Result:= 2;
exit;
end;
Result:= 0;
end;
function doo2: integer;
Procedure exitIfFalse(const AResult: boolean; const AResultCode: integer);
begin
if not AResult then begin
Result:= AResultCode;
Abort;
end;
end;
begin
Result:= -1;
try
exitIfFalse(foo(42), 1);
exitIfFalse(foo(8), 2);
Result:= 0;
except
on e: EAbort do begin
end;
end;
end;
function doo3: integer;
begin
exitIfFalse(foo(42), 1);
exitIfFalse(foo(8), 2);
Result:= 0;
end;
source to share
Later versions of Delphi (2009 and newer) are coming up: they allow you to write
function doo3: integer;
begin
if not foo(42) then Exit(1);
if not foo(8) then Exit(2);
Result:= 0;
end;
Note how the new form Exit(value)
can be combined with the more traditional one Result
.
Delphi 2007 does not officially support this or anything like that.
A completely unsupported hack might work for you: Andreas Hausladen DLangExtensions (be sure to use a legacy build) provides this syntax for Delphi 2007 as well.
source to share