I'm using Delphi 2007 and was wondering if the following is possible, if not is it then possible in another version of Delphi.
My code at the moment looks like doo1
but what
I would like to have is something like doo3
.
I've made doo2
and it works but I'd prefer
having the exitIfFalse
function in one place
instead of as a subprocedure 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;
Later versions of Delphi (2009 and newer) come close: they let you 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 Exit(value)
form can be combined with the more traditional Result
.
Delphi 2007 does not support officially this, or anything similar.
A completely unsupported hack may work for you: Andreas Hausladen's DLangExtensions (make sure to use an older build) provides this syntax for Delphi 2007 too.