So, at my present job the primary technology platform is c# and most of the people here are not familiar with closures. I wasn't too familiar with them either until I started looking at the hole in the middle pattern and some of the new features in .net like anonymous delegates. Now that I have been getting familiar them I am finding them the bees knees and I try to use closures and anonymous delegates whenever I get the chance.

Unfortunately, most programmers I run into aren't familiar with these concepts, so I thought I would try and shed some light on this subject and why I find closures and more specifically, anonymous functions cool.

First off, what is a closure? Wikipedia gives a good explanation. The key concept is that a closure is a function with some private variables/state that belong to it, in addition to any parameters or local variables belonging to the function. So I think of a closure as an object like structure that contains a function and some additional state that it can access.

So whats different about this compared with object oriented programming or a regular function? Someone can create an object that has both data and methods that can access that data or one can also create functions with parameters. The power of anonymous functions is that you can get some object like properties in that you can associate data with a function without specifying any class definitions. This allows you to use anonymous functions in places where they aren't expecting a class but instead pass in your function which will also have the state needed for it to run.

Some examples will clarify. Here is a simple example from javascript.


function popupWindow(content,name)
{

top.consoleRef = window.open(',name,
'width=850,height=680,menubar=1,resizable=1');
self.setTimeout(writeToPopup(content),500);

}

function writeToPopup(content)
{

return function() {
top.consoleRef.document.write(content);
top.consoleRef.document.close();
}

}

I was dealing with a bug in Internet Explorer where the popup freezes when writing to it. Apparently this is a known issue and the workaround is to limit your writes to the popup and to introduce a delay after launching the window and writing to it. The solution was to use setTimeout function to introduce a delay between popping the window up and writing to it. The problem was that the syntax of setTimeout makes it difficult to pass arguments to the function that it calls after the timeout. One can essentially only call a no argument function or a function with some string parameter built on the fly. But this did not quite meet my needs as I was passing in html. So I found this blog which was passing a closure to the setTimeout function.

I found this very cool in its simplicity. What happens above is that the function call writeToPopup is evaluated and returns an anonymous function. This function also includes the local state of the context where it was created. In this example the variable content is the only such state. So when writeToPopup returns the anonymous function the variable content is accessible in the anonymous function even though it is not a parameter or a global variable.

We could have written the function in a different way.

function popupWindow(content,name)
{

top.consoleRef = window.open(',name,
'width=850,height=680,menubar=1,resizable=1');
self.setTimeout( function(){
top.consoleRef.document.write(content);
top.consoleRef.document.close()}, 500);

}


The only difference here is that the anonymous function is created in a different context so it would have both content and name as state available to the anonymous function.

It takes a while before the power of closures and anonymous functions hit you. They allow you to do things that should be simple without using things like global variables and without defining specific contracts, classes or function signatures. So, next time you want to find a way to attach some state without passing it along as a parameter or object think of closures.

Of course this is only the tip of the iceberg. To really get to know these concepts I suggest trying to solve a problem like writing a factorial function without using iteratation and only uses anonymous functions for recursion. Here is a good article if you want to see the answer.