The post I made yesterday on anonymous methods, a new feature in Delphi 2009, stirred controversy. I agree on the readability comments, but you should also consider that using three nested anonymous methods was quite a stretch, not a common usage scenario.

Let's start from the beginning and examine only one step. I want to make an HTTP call and process the result. This has to be done in a thread, since I don't want it to be blocking. So whether you use anonymous methods or not you need to define a custom TThread class. Now suppose you want to use the same thread class(or its HTTP support code) for slightly different situations. You have two traditional options:

  • 1. Inherit a class for each usage scenario and use the tempalte pattern: the thread execute method will call a virtual function each specific class can override. Nice, but in case the specific code is limited, creating many similar classes, mostly used only for a single object in a specific situation is far from a nice architecture.
  • 2. Delphi classic alternative to inheritance is to use events. In fact, you don't inherit from TButton to override the Click method, but assign an external procedure to the event, using method pointers. Each customization is in a separate method you assign.

Method pointers and anonymous methods are not that different. In one case you can write the procedure in-place, but that is an option. For readability, you can write the code I had yesterday as a series of separate functions, each assigned to an anonymous methods pointer to be called later on. Will this be more readable? Possibly, even if (from JavaScript experience) I think it is mostly a matter of getting used to a style or another. In other words, syntax aside, the concept of an anonymous method is not far from that of a method pointer, but the fact they introduce a new lifetime model for variables can help.

This bring me to another point, why not keep using method pointer. Having to allocate memory for every invocation of an event (in case of execution of code in parallel) would be far from trivial in many case in which anonymous methods just "magically" work, As a commenter noted about my yesterday post, if you hit the button many times the nHit stack-based variable gets duplicated and capture for each anonymous method invocation, so not only if lives beyond its original stack location, but you can have multiple instances at the same time...

Would this mean each and every Delphi code would benefit from this new technology? Of course not, I think it is useful only in a fraction of cases. I remain convinced that an Ajax-like call is a nice scenario and that it will take some time for the Delphi community at large to master this new language feature.