2010
02.10

Over the past year the way I have developed code has been changing.  I have started to think differently about how I implement my code moving beyond traditional object orientated programming, making use of numerous functional concepts in my solutions.  I think this is due to the fact I have been trying to expose myself to as much code as possible across many different languages and platforms and somethings have just stuck.

One of the concepts I have came to know and love is that of a closure.  This was first exposed to me when C# started to incorporate more functional aspects into the language such as anonymous methods as first class citizens and later lambda expressions.

You might think this is quite odd that I specially call out closures & anonymous functions as being a functional concept, as closures are used heavily in dynamic languages due to the fact functions can be passed about as first class citizens. Passing functions about is the very nature of a functional language.

This is what Wikipedia has to say:

In computer science, a closure is a first-class function with free variables that are bound in the lexical environment. Such a function is said to be “closed over” its free variables. A closure is defined within the scope of its free variables, and the extent of those variables is at least as long as the lifetime of the closure itself.

The closure aspect is simple… the anonymous function is “Trapping” the local variable within the functions context.  That means the local variable in question will remain in scope for the duration of the lifetime of the anonymous function. In the examples below I declare anonymous functions called “closure” and I en-close around variable called “x”.

So here is an example of a closure in my language of the month Groovy:

def loopTo(n, closure)
{
	for(int i = 0; i < n; i++)
	{
		if(closure(i))
			println i
	}
}

//Our variable to be "Closed Over"
int x = 2

// I like this syntax of '{ }' to create an anonymous method,
// in Groovy we can use 'it' by default
// to reference an undefined but passed parameter.
loopTo(100, { it % 2 == x })

Now in JavaScript:

function loopTo(n, closure){
	for(i = 0; i < n; i++){
		if(closure(i)){
			alert(i);
		}
	}
}

//Our variable being "Closed over"
var x = 0;
// In JS we use the 'function' keyword and specify the parameter
loopTo(10, function(i){
	return i % 2 == x;
});

Now in C#:

static void Main(string[] args)
{
    //Our variable being "Closed over"
    int x = 0;

    // In C# we can use a lambda expression.
    LoopTo(100, num => num % 2 == x );
}

// As C# is strongly typed we define the expected
// expression type as a 'Func<param, return type>'
public static void LoopTo(int n, Func<int, bool> closure)
{
    for (int i = 0; i < n; i++)
    {
        if(closure(i))
            Console.WriteLine();
    }
}

And now in Scala:

// Scala is sweet we store our range rather than writing a loop,
// then iterate over the list passing the index 'i' into our closure.
def main(args: Array[String]) :Unit = {
    val range = 0.until(100);
    range.foreach(num =>  if(closure(num)) println(num) );
}
//Our variable to be "Closed over"
val x:int = 0
// Our function is defined like so
def closure(num : Int) = {  num %  2 == x;  }

We can copy the Scala way in C#.
We had to cheat a tad and write a funky ‘Until’ C# Extension Method.
This gives us a nice fluent way to create a range of integers stored as a list like so:

public static void Main(string[] args)
{
    //Extension method 'Until' defined later in this post
    var range = 0.Until(100);
    range.ForEach(num => { if(Closure(num)) Console.WriteLine(num); });
}
int x = 0;
// Our function definition in C#
private static readonly Func<int, bool> Closure = num => num % 2 == x;
public static class Extensions
{
    // Called like so: 0.Until(100)
    public static List<int> Until(this int lower, int upper)
    {
        var range = new List<int>();

        for (int i = lower; i <= upper; i++)
        {
            range.Add(i);
        }

        return range;
    }
}

This is what the code would look like without using anonymous functions:

private static void Main(string[] args)
{
    LoopTo(100);
}

public static void LoopTo(int n)
{
    int x = 0;
    for (int i = 0; i < n; i++)
    {
        //Our logic for filtering is tied to the control structure
        if (i % 2 == x)
            Console.WriteLine(i);
    }
}

As you can see the code is not only verbose but breaks a the DRY rule (Don’t Repeat Yourself).  Closures are powerful because they encapsulate what might almost be described as a “Strategy”. You have separated out the control structure from the logic. This is the strategy design pattern.

Closures become powerful when your reach the level of understanding that the encapsulation of logic allows for some really powerful composition of “Strategy”.

I find this really intriguing.  I like languages, and I love the idea creating domain specific languages / fluent APIs which make the definition of “Strategy” trivial to the end user.  By combining closures (via currying) or by logically appending delegates together we can create something truly powerful.

If you didn’t know what anonymous functions & closures were when you started to read this post, then hopefully you do now and maybe you can see why they are worth using.

Just some food for thought.

2010
02.10

I have decided to switch to using Alex Gorbatchev’s Syntax Highlighter.  It is probably the nicest one out there with funky quick copy, print and view source features.

Some Groovy:

def pickEven(n, block)
{
	for(int i = 2; i <= n; i +=2)
	{
		block(i)
	}
}

pickEvent(10, { println it })

Some Ruby:

puts "hi"

Some JavaScript:

/* SyntaxHighlighter */
function foo(){
	// it works!
}

Some C#:

void DoSomething()
{
	ParseALambdaExpression(email => email.Contains("@"));
}

void ParseALambdaExpression(Expression<func<<string , bool>> func)
{
	BinaryExpression body = func.Body as BinaryExpression;
}
2010
02.09

SDHC_smallIt was about 4 months ago when I through the idea out on twitter of an open developer event in Belfast which encouraged developers from all backgrounds to come together for the cross pollination of ideas and some communal hacking. 

This was picked up by Blaine Cook and David Wilson and soon after it became a reality!  They had been thinking for a while about setting up an event in the guise of Super Happy Dev House here in Northern Ireland.

We made one twist thou… we held it in a Castle!

SHDC0-5SHDC0-4 

The first ever Super Happy Dev Castle is now over… and what an event it was.

We had some exceptional hosts (Blaine & Maurine) for the inaugural event, who we simply cannot thank enough! SHDC #0 took place on Saturday 6th February and ran through to the Sunday morning.

SHDC0-0

We had around 24 people throughout the course of the all night hack-a-thon with projects ranging from ultra fast data processing and real time search of Translink route data to the release of an open source JavaScript ePub library.

SHDC0-3I personally worked on Sourced, and open source light weight SFTP editor written in Java… it’s something like Coda.  I worked on refactoring the design into a more testable MVC structure. I also toyed with using Groovy as the language for the UI aspect of the application and the creation of a plug-in API which would allow for a plug-in DSL to be created in Groovy.

SHDC0-6

There was plenty of craic (maybe too much at times)… and lots of nerdy conversations.  The crowd was mixed, ranging from hardcore hardware hackers through to php script kiddies. (Even a few designers managed to sneak in to do some wire framing =P)!

A good time was had by all!  The next event will hopefully be held in just over a months time with a venue yet to be confirmed.

We are also toying with the idea of making some T-Shirts, everyone knows nerds <3 T-Shirts!!

image

Happy Hacking!