Take every thought captive.

What is a closure?

A closure is a mechanism that allows functions to gain access to variables that are outside of the functions definition while maintaining functional purity. But wait - doesn't functional purity mean everything is encapsulated in the function? How can this be?

First lets look at a simple closure.


	public static void Main (string[] args)
	{
		Console.WriteLine (StringValidation()("xxx")); // False
		Console.WriteLine (StringValidation()("xxxabcxxx"));  //True				
	}		
		
	public static Func StringValidation()
	{
		string validationPattern = "abc";	
		return delegate (string text) 
			{  
				return text.Contains(validationPattern); 
			} ;
	}
	

We get False then True.

The StringValidation function returns a function that validates any string we pass it. (Functions creating functions!) But look at the validationPattern variable. Why has that variable not fallen out of scope? That is a closure. The variable that a function has access to at the time it was created can be enclosed in that function. Now lets look at a more complex closure.


	public static void Main (string[] args)
	{
		string validationPattern = "abc";	
		Console.WriteLine (StringValidation(validationPattern)("xxx"));  //False
		
		validationPattern = "xxx";	
		Console.WriteLine (StringValidation(validationPattern)("xxx"));  //True
		Console.WriteLine (StringValidation(validationPattern)("xxxabcxxx"));	//True			
	}		
		
	public static Func StringValidation(string validationPattern)
	{
	
		return delegate (string text) 
		{  
			return text.Contains(validationPattern); 
		} ;
	}
	

We get False, True, True.

Wait. What just happened? I thought the string value would be passed by value and each function would have it's own copy of the value at the time anonymous function was created. Also isn't this a very non-functional thing to do? Is functional programming all about pure functions that are not affected or effect state. Aren't functions supposed to always behave the same regardless of state? Yes this is a very non-functional thing to do. But it is not the closure that is causing the problem. It is the mutating variable. Changing validationPattern from "abc" to "xxx" is the non-functional practice. A functional purist would want all variables to be final. Once you assigne a variable it never changes.

So why use closures?

So why use closures? Because when implemented correctly closures allow functions to maintain state in a functional way. Lets say we had a function that was responsible for telling a bar tender application when a customer has had too much to drink. In OO we would create a customer object with the property PercentDrunkness and a method called Drink( double percentAlhocol, double pints ) that calculated the PercentDrunkness.


	class MainClass
	{
		public static void Main (string[] args)
		{
			Customer joe = new Customer();
			joe.Drink(.1, 1.0);
			Console.WriteLine(Convert.ToString(joe.PercentDrunk));
			joe.Drink(.3, 1.0);
			Console.WriteLine(joe.PercentDrunk.ToString());
			joe.Drink(.3, 1.0);
			Console.WriteLine(joe.PercentDrunk.ToString());
		}		
	}	
	public class Customer
	{
		public Customer ()
		{
			percentDrunk = 0.0;
		}
		
		private double percentDrunk = 0.0;
		public double PercentDrunk
		{
			get { return percentDrunk; } 
		}	
		public void Drink(double percentAlcohol, double pints) 
		{  
			percentDrunk 	= (percentAlcohol * pints)  + percentDrunk;
		}	
	}
	

Implemented as a closure we would create a new function to track a customer's level of inebriation. That function encapsulates or encloses the state of the drunkenness.

 
	public static void Main (string[] args)
	{
		Func DrunkMeter = PercentDrunk();
		Console.WriteLine (DrunkMeter(.1, 1).ToString());  //.01
		Console.WriteLine (DrunkMeter(.3, 1).ToString());  //.04
		Console.WriteLine (DrunkMeter(.3, 1).ToString());  //.07
	}		
		
	public static Func PercentDrunk()
	{
		double percentDrunk = 0.0;
		return delegate (double percentAlcohol, double pints) 
		{  
			percentDrunk = (percentAlcohol * pints)  + percentDrunk;
			return  percentDrunk; 
		} ;
	}	
	 

And why is this better?

Closures allow us to dynamically change the way our objects behave in ways that are not practical without them. Lets continue our example. Lets say we needed to account for different customer types and we want to add a new method called Eat(). In OO we would have to create a Customer object and extend that object by creating two new objects LittleLady : Customer and BigGuy : Customer. Then each sub-class would override the Drink() and Eat() methods. All is good until we find out that our instance of LittleLady actual drinks like a BigGuy. No problem, cast the instance LittleLady to BigGuy right? Wrong. This instance of LittleLady drinks like and BigGuy but she doesn't Eat() like one.

In OO we have a problem because we can change the data about our objects, but changing functionality is not so easy. But if we had created closures instead of inherited objects we could have done this easily. All we need is a class Customer. Customer has two properties of type Action<>, one for Drink and one for Eat. Then we create closures and assign closures to each Action<> property. Now we can mix and match behavior. Our BigGuy can Eat() like a LittleLady and our LittleLady can Drink() like a BigGuy.