A somewhat baffling problem suggested by
this post and answers to it.
Let's say I'm extending/replacing a function like, for example,
FindAllFiles() to allow for a procedure/function to be called on each file found, which can easily be done by making use of
TFileSearcher's events.
Now, the type of the "callback" parameter could be declared either as a normal function/procedure or as a method (a function/procedure
of object), so one would need two overloaded functions, each requiring one type or the other.
The question, now, is how to avoid duplicating code, that is, having two functions with basically the same code except for the callback without complicating matters too much. I came up with the concept of a
third overload doing the main thing and to which it is passed a record such as:
TCallback = record
case IsMethod: Boolean of
True: (MethodCallback: TMethodCalback);
False: (NormalCallback: TNormalCallback);
end;
This would allow us to make, from the first two overloads, something like:
procedure FindMostFiles(..., const OnFileFound: TNormalCalback =nil);
var
Callback: TCallback;
begin
{ Call the third, full overloaded version}
Callback.IsMethod := False;
Callback.NormalCallback := OnFileFound;
FindMostFiles(..., Callback);
end;
But I don't really like this kind of solution, so
now the question: Can someone suggest a better alternative for calling what is, basically, the same code allowing it to be passed either a normal callback or a method?
BTW, to prune the solution tree: yes, I though of using a TFileSearcher, setting its OnFileFound directly if we are called with a method or using an internal event handler and calling the function/proc indirectly if passed a normal proc/function.
Any more?
Thanks for playing!
