Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Wrap function calls generic in Delphi

I have different functions in a class that are called. Now I want to implement a custom global error Management in generic manner.

My function are:

function TTestClass.DoWorkA(parameter : String): boolean;
begin
  try
    result := internalClass.DoWorkA(parameter);
  except
    DoStuff();
  end;
end;

function TTestClass.DoWorkB(): String;
begin
  try
    result := internalClass.DoWorkB();
  except
    DoStuff();
  end;
end;

I have to insert the try except block in every Method. This block doesn't change and is always the same. Now I want to solve this problem in a generic manner (pseudo code):

function TTestClass.DoWorkA(parameter : String): boolean;
begin
   result := DoWork<boolean>(internalClass.DoWorkA,parameter);
end;

function TTestClass.DoWorkB(): String;
begin
  result := DoWork<string>(internalClass.DoWorkB);
end;

function TTestClass.DoWork<T>(function : TFunction;parameter : TParameters): T;
begin
  try
     result := Call(function,parameter);
  except
    DoStuff();
  end;


end;

Something like this came to mind but I didn't find a way to solve it with this code.

Is there a way to implement something like this in delphi?

like image 333
frugi Avatar asked Dec 05 '25 03:12

frugi


1 Answers

You can use generics and anonymous methods for this:

function TTestClass.DoWork<T>(Func: TFunc<T>): T;
begin
  try
    result := Func();
  except
    DoStuff();
  end;
end;

You can call it readily like this:

function TTestClass.DoWorkA(parameter : String): boolean;
begin
  result := DoWork<boolean>(
    function: Boolean
    begin
      Result := internalClass.DoWorkA(parameter);
    end;
  );
end;
like image 157
David Heffernan Avatar answered Dec 07 '25 16:12

David Heffernan