BT

Facilitating the Spread of Knowledge and Innovation in Professional Software Development

Write for InfoQ

Topics

Choose your language

InfoQ Homepage News Using Closures to Improve API Design and Usage

Using Closures to Improve API Design and Usage

This item in japanese

Some APIs such as those that perform complex parsing often expose intermediate results via events. For example, the XDocument.Validate extension method uses an event to notify the program that there are validation errors.

In traditional .NET programming, catching these events would mean creating a separate function for each event. Since there is no direct way to pass additional information into or out of the event handler, these functions are normally implemented inside a throwaway class.

Eric White uses closures to demonstrate a better way. A closure is a special case of the lambda or anonymous inline function. What makes a closure special is that can reference variables that are not local to it, but are local to the function that contains the lambda. This allows Eric to keep the event handling logic local to the function. The below line shows the closure being created and passed to the Validate function:

snippet.Validate(schemas, (o, e) => errors += e.Message + Environment.NewLine);

As a side note, closures in C# and VB are implemented as anonymous classes that contain the necessary member variables. The "enclosed" variables are moved to the new class and referenced by both the original function and any anonymous functions it contains.

Rate this Article

Adoption
Style

BT