In my previous post I pointed to some information from Mr. Fowler on closures as well as a link to a page that compares closures in Ruby with what we now have in C# 2.0.
This post is an attempt to write down my understanding of closures as to make it stick a little bit better then it did when I just read a couple overviews.
If we hop in the “way back machine” we can find closure support in languages that have been around for a long time, such as smalltalk. Those in the smalltalk world have been working with closures, which apparently are called blocks, for a long time. One of the more popular languages at the present time that supports closures is Ruby. I’m pretty sure most dynamic languages support closures in some form or another but I could definitely be making that up.
Anyway back to the task at hand, what is this closure thing we’re speaking of and why should anyone care? Basically a closure is a block of code that you can pass as an argument to a method. Different languages support the passing of parameters to the “block” of code in different ways. In Ruby their passed in between vertical bars like |so|. In C# 2.0 they’re just declared as arguments when we define an anonymous delegate.
As Martin Fowler points out closures sound an awful lot like function pointers. Although they’re similar there are a couple differences. The first main difference is that closures can refer to the variables that are in scope at the time the closure if called. This means that our closures can reference variables declared outside of the closure. Try that with function pointers or anonymous inner classes, I dare you!?! Ok, not really. Moving on…
Ok, so that might not be that big of a deal, so let’s move onto the bigger differences. So the “first crucial point about closures is that they are a block of code plus the bindings to the environment that they came from.” (Fowler). Ok, so they’re not just out in space with no connection back to their home. They actually have a connection back (binding) to the environment that they came from.
The things that I found interesting about closures is how it lets you express things in code. Although the syntax takes a little getting used to using closures to perform filtering, sorting, converting, and all that other fun seems like it could reduce the amount of code it takes to do such things by a pretty good bit.
The important thing will be to ensure you don’t start using closures all over the place. The simplicity could lead to closures scattered all over the place which could get ugly fast. Just like anything else it’s probably a good idea to encapsulate the closures within you’re business objects. Or not :-)
Looking for more? Check out http://blogs.msdn.com/kcwalina/archive/2004/06/22/162533.aspx for more API’s that support closures (aka anonymous delegates).