Chapter Anonymous Methods

The Delphi language has had procedural types (that is, types declaring pointers to procedures and functions91) and method pointers (that is, types declaring pointers to methods) for a long time. Although you might seldom use them directly, these are key features of Delphi that every developer works with. In fact, methods pointers types are the foundation for event handlers in the VCL: every time you declare an event handler, even a pure

91 In case you want to learn more, procedural types are covered in Chapter 6 of Essential Pascal, 4th edition; method pointer types are describe in the books of my Mastering Delphi series.

ButtonlClick you are in fact declaring a method that will be connected to an event (the OnClick event, in this case) using a method pointer.

Anonymous methods extend this feature by letting you pass the actual code of a method as a parameter, rather than the name of a method defined elsewhere. This is not the only difference, though. What makes anonymous methods very different from other techniques is the way they manage the lifetime of local variables.

The definition above matches with a feature called closures in many other languages, for example JavaScript. If Delphi anonymous methods are in fact closures, how come CodeGear refers to them using a different term? The reason is that C++Builder has been using the term closures for what we in Delphi call event handlers, so having a different feature with the same name would have been confusing. Moreover, the C# language uses the term anonymous methods for a similar mechanism as Delphi has, so it makes sense to use a similar moniker.

If anonymous methods are a brand new feature for Delphi, they've been around in different forms and with different names for many years in other programming languages, most notably dynamic languages. I've had extensive experience with closures in JavaScript, particularly with the jQuery92 libraries and AJAX calls. The corresponding feature in C# is called an anonymous delegate.

But I don't want to devote time comparing closures and related techniques in the various programming languages, but rather describe in detail how they work in Delphi 2009.

Was this article helpful?

0 0
Project Management Made Easy

Project Management Made Easy

What you need to know about… Project Management Made Easy! Project management consists of more than just a large building project and can encompass small projects as well. No matter what the size of your project, you need to have some sort of project management. How you manage your project has everything to do with its outcome.

Get My Free Ebook

Post a comment