[fpc-devel] Delphi anonymous methods

Martin lazarus at mfriebe.de
Mon Mar 4 12:17:53 CET 2013


On 04/03/2013 04:54, Boian Mitov wrote:
> Here is example:
>
> Parallel execution with selection of executor:
>
> for i := 0 to AMaxScaleIndex - 1 do
>  begin
>  APerIterationLocations.Add( TRTDynamicList<TVLImageRect>.Create() );
>  AExecutionTask.Add( AExecutor.Execute(
>      procedure()
>      begin
>        ProcessOne( levelScale[ i ], img, hitThreshold, winStride, 
> padding, APerIterationLocations[ i ] );
>      end
>    ));
>
>  end;
>
> In this case, not only you save declaration, you save the need to 
> write a whole new class just for the task.
> This code reduced well over 30 lines of code alone.
> I have a lot of other examples as well ;-) .

Ok, I can see the closure helping, but why the anonymous procedure?

If FPC would offer something like this:

Procedure Foo;
var
   // your locals
      procedure  Bar(); closure;
        begin
          ProcessOne( levelScale[ i ], img, hitThreshold, winStride, 
padding, APerIterationLocations[ i ] );
        end
begin
   // your code from above
   for i := 0 to AMaxScaleIndex - 1 do
    begin
    APerIterationLocations.Add( TRTDynamicList<TVLImageRect>.Create() );
    AExecutionTask.Add( AExecutor.Execute( @Bar  ));
end;

I added:
  - the name "Bar"
- Used is at reference
- the keyword "closure"

The above code would then create the exact same closure, as your code 
does. And it does not need an anonymous method.

Of course for portability of Delphi code, in {$mode Delphi}  you need 
the anonymous method.
But the argument on this thread was, that you needed it, because 
anonymous functions allowed to do things not possible (or very hard) 
without. And that argument still does not hold up. It only applies to 
closures.

There is only one other difference between the 2. And that is the 
subjective preference where you like the code.
- You may find it more readable to see see code of a function in-lined. 
So you do not need to scroll.
- You may prefer the shorter body of the none anonymous version. After 
all, if you give it a meaningful name, it should read as easy as the 
inlined version.
But that is personal preference. It can not be argued on.




More information about the fpc-devel mailing list