BT

InfoQ Homepage News Using Closures to Improve API Design and Usage

Using Closures to Improve API Design and Usage

Bookmarks

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

Hello stranger!

You need to Register an InfoQ account or or login to post comments. But there's so much more behind being registered.

Get the most out of the InfoQ experience.

Allowed html: a,b,br,blockquote,i,li,pre,u,ul,p

Community comments

  • Thanks for bringing attention to this language feature

    by Faisal Waris /

    Your message is awaiting moderation. Thank you for participating in the discussion.

    Some aspects of your program can be done much more cleanly with closures.

    Most new mainstream languages support closures (VB, C#, Ruby, Python, javascript) as did the pioneering languages of old (LISP, Smalltalk, etc). Java is a notable exception. However not everyone (esp. C# / VB community) is knowledgeable or comfortable with this feature and its use so additional awareness is goodness.

    Interestingly, async programming benefits greatly from closures - as evidenced by the popularity of AJAX. Closure support in the DLR helps Silverlight programs immensely because all server-side calls are handled asynchronously out of the box.

Allowed html: a,b,br,blockquote,i,li,pre,u,ul,p

Allowed html: a,b,br,blockquote,i,li,pre,u,ul,p

BT

Is your profile up-to-date? Please take a moment to review and update.

Note: If updating/changing your email, a validation request will be sent

Company name:
Company role:
Company size:
Country/Zone:
State/Province/Region:
You will be sent an email to validate the new email address. This pop-up will close itself in a few moments.