BT

Using Closures to Improve API Design and Usage

by Jonathan Allen on Sep 04, 2008 |

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.

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.

Tell us what you think

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

Email me replies to any of my messages in this thread

Thanks for bringing attention to this language feature by Faisal Waris

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

Email me replies to any of my messages in this thread

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

Email me replies to any of my messages in this thread

1 Discuss

Educational Content

General Feedback
Bugs
Advertising
Editorial
InfoQ.com and all content copyright © 2006-2014 C4Media Inc. InfoQ.com hosted at Contegix, the best ISP we've ever worked with.
Privacy policy
BT