Liam McLennan

Building a new blog engine with node.js, geddy and github gists Jun 01

I wrote a very simple blog engine, and created a new blog, and wrote about the process. Enjoy. It has node.js and geddy and markdown and github gists.

Not posting here any more Jun 04

I have been cross posting for a long time and now I can no longer be bothered. If you have benefited from the content that I have shared here then consider subscribing to my blog at hackingon.net.

Mocking Extension Methods on NHibernate.ISession Mar 20

I have written about adding support for specifications to NHibernate’s ISession type. Shortly afterwards Paul Stovell moaned on twitter that no one had demonstrated how to mock ISession. Since my implementation relied upon an extension method (QueryBySpecification) I googled how to mock extension methods – and discovered that you can’t. What I did find was Daniel Cazzulino’s post about converting extension methods to methods that return a Func that exposes your extension method. That way you can replace the Func for your tests. This changed my api from

session.QueryBySpecification(canDriveSpecification);

to

session.Spec().Query(canDriveSpecification);

My new test, with mocking, is

[Test]
public void MockASpecification()
{
   var canDriveSpecification = new PeopleOverAgeSpecification(16);
   var queryer = Substitute.For<ISpecificationQueryer>();
   queryer.Query(Arg.Any<PeopleOverAgeSpecification>()).Returns(new List<Person> { new Person() });
   SpecificationExtensions.SpecificationQueryerFactory = s => queryer;
   var allPeopleOfDrivingAge = session.Spec().Query(canDriveSpecification);
   Assert.AreEqual(1, allPeopleOfDrivingAge.Count());
}

The full code is available on the QueryClasses project on github.

JavaScript Class Patterns – In CoffeeScript Mar 18

Recently I wrote about JavaScript class patterns, and in particular, my favourite class pattern that uses closure to provide encapsulation. A class to represent a person, with a name and an age, looks like this:

var Person = (function() {
  // private variables go here
  var name,age;
  
  function constructor(n, a) {
    name = n;
    age = a;
  }

  constructor.prototype = {
    toString: function() {
      return name + " is " + age + " years old.";
    }
  };
  
  return constructor;  
})();

var john = new Person("John Galt", 50);
console.log(john.toString());

Today I have been experimenting with coding for node.js in CoffeeScript. One of the first things I wanted to do was to try and implement my class pattern in CoffeeScript and then see how it compared to CoffeeScript’s built-in class keyword. The above Person class, implemented in CoffeeScript, looks like this:

# JavaScript style class using closure to provide private methods
Person = (() ->
	[name,age] = [{},{}]
		
	constructor = (n, a) ->
		[name,age] = [n,a]
		null
		
	constructor.prototype = 
		toString: () ->
			"name is #{name} age is #{age} years old"
	
	constructor
)()

I am satisfied with how this came out, but there are a few nasty bits. To declare the two private variables in javascript is as simple as var name,age; but in CoffeeScript I have to assign a value, hence [name,age] = [{},{}]. The other major issue occurred because of CoffeeScript’s implicit function returns. The last statement in any function is returned, so I had to add null to the end of the constructor to get it to work.

The great thing about the technique just presented is that it provides encapsulation ie the name and age variables are not visible outside of the Person class. CoffeeScript classes do not provide encapsulation, but they do provide nicer syntax. The Person class using native CoffeeScript classes is:

# CoffeeScript style class using the class keyword
class CoffeePerson
	constructor: (@name, @age) ->
	
	toString: () ->
		"name is #{@name} age is #{@age} years old"
		
felix = new CoffeePerson "Felix Hoenikker", 63
console.log felix.toString()

So now I have a trade-off: nice syntax against encapsulation. I think I will experiment with both strategies in my project and see which works out better.

Paying it Forward Mar 18

image You’re a talented guy (or girl). You’ve done alright. Years of hard work and stick-to-it-ive-ness have paid off and left you with plenty and an opportunity to make a positive difference to someone else.

And then there are people with less than they need. Sometimes all they need to help themselves is a start. Opportunity International provide micro financing to help people grow their small businesses so that they can afford food, shelter, water and education.

microfinance to solve poverty

 

MonsoonerOrLater

imageThis June, Chris, Angus (my brother) and I are travelling to India, entering into a rickshaw race and raising money for charity (Opportunity International and Round Table India).

The Deccan Odyssey is a nine day rally, racing up the coast of India from Goa to Mumbai in a three wheeled motorbike.

If you would like to support us, please make a tax deductable donation via our secure site at GoFundraise.

For more information take a look at the MonsoonerOrLater site.

If you live in Brisbane come along to An Evening With MonsoonerOrLater. The entry fee includes a three-course Indian meal, live music, henna tattooist, chilli eating competition, best bollywood dance off, Dhalsim Vs Dhalsim Street fighter, Delhi Belly Bet, Auctions and Prizes. All profits go to our charities: Round Table India and Opportunity International.

Using Query Classes With NHibernate Mar 11

Even when using an ORM, such as NHibernate, the developer still has to decide how to perform queries. The simplest strategy is to get access to an ISession and directly perform a query whenever you need data. The problem is that doing so spreads query logic throughout the entire application – a clear violation of the Single Responsibility Principle. A more advanced strategy is to use Eric Evan’s Repository pattern, thus isolating all query logic within the repository classes.

I prefer to use Query Classes. Every query needed by the application is represented by a query class, aka a specification. To perform a query I:

  1. Instantiate a new instance of the required query class, providing any data that it needs
  2. Pass the instantiated query class to an extension method on NHibernate’s ISession type.

To query my database for all people over the age of sixteen looks like this:

[Test]
public void QueryBySpecification()
{
   var canDriveSpecification = 
	  new PeopleOverAgeSpecification(16);
		
   var allPeopleOfDrivingAge = session.QueryBySpecification(canDriveSpecification);
}

To be able to query for people over a certain age I had to create a suitable query class:

public class PeopleOverAgeSpecification : Specification<Person>
{
  private readonly int age;

  public PeopleOverAgeSpecification(int age)
  {
      this.age = age;
  }

  public override IQueryable<Person> Reduce(IQueryable<Person> collection)
  {
      return collection.Where(person => person.Age > age);
  }

  public override IQueryable<Person> Sort(IQueryable<Person> collection)
  {
      return collection.OrderBy(person => person.Name);
  }
}

Finally, the extension method to add QueryBySpecification to ISession:

public static class SessionExtensions
{
  public static IEnumerable<T> QueryBySpecification<T>(this ISession session, Specification<T> specification)
  {
      return specification.Fetch(
          specification.Sort(
              specification.Reduce(session.Query<T>())
          )
      );
  }
}
The inspiration for this style of data access came from Ayende’s post Do You Need a Framework?. I am sick of working through multiple layers of abstraction that don’t do anything. Have you ever seen code that required a service layer to call a method on a repository, that delegated to a common repository base class that wrapped and ORMs unit of work? I can achieve the same thing with NHibernate’s ISession and a single extension method.

If you’re interested you can get the full Query Classes example source from Github.

JavaScript Class Patterns Revisited: Endgame Feb 17

 

imageI recently described some of the patterns used to simulate classes (types) in JavaScript. But I missed the best pattern of them all. I described a pattern I called constructor function with a prototype that looks like this:

function Person(name, age) {
  this.name = name;
  this.age = age;
}

Person.prototype = {
  toString: function() {
    return this.name + " is " + this.age + " years old.";
  }
};

var john = new Person("John Galt", 50);

console.log(john.toString());

and I mentioned that the problem with this pattern is that it does not provide any encapsulation, that is, it does not allow private variables. Jan Van Ryswyck recently posted the solution, obvious in hindsight, of wrapping the constructor function in another function, thereby allowing private variables through closure. The above example becomes:

var Person = (function() {
  // private variables go here
  var name,age;
  
  function constructor(n, a) {
    name = n;
    age = a;
  }

  constructor.prototype = {
    toString: function() {
      return name + " is " + age + " years old.";
    }
  };
  
  return constructor;  
})();

var john = new Person("John Galt", 50);
console.log(john.toString());

Now we have prototypal inheritance and encapsulation. The important thing to understand is that the constructor, and the toString function both have access to the name and age private variables because they are in an outer scope and they become part of the closure.

What ‘enterprise’ doesn’t understand about risk Feb 14

Enterprises (large bureaucracies) obsess about risk. I think it is because of the inertia generated by the process and politics that they have to deal with.

The trouble is that they respond to risk in precisely the wrong way: by adding complexity. Need to call a method? Better wrap it in WCF service. Need to talk to another application? Better hook a message queue to a service bus connected to a biztalk sharepoint – on Oracle. Here is a simple guide:

Complexity increases risk. Simplicity reduces risk.

JavaScript Class Patterns Feb 06

To write object-oriented programs we need objects, and likely lots of them.

JavaScript makes it easy to create objects:

var liam = {
  name: "Liam",
  age: Number.MAX_VALUE
};

But JavaScript does not provide an easy way to create similar objects. Most object-oriented languages include the idea of a class, which is a template for creating objects of the same type. From one class many similar objects can be instantiated.

cookie cutter

Many patterns have been proposed to address the absence of a class concept in JavaScript. This post will compare and contrast the most significant of them.

Simple Constructor Functions

Classes may be missing but JavaScript does support special constructor functions. By prefixing a call to a constructor function with the ‘new’ keyword we can tell the JavaScript runtime that we want the function to behave like a constructor and instantiate a new object containing the members defined by that function. Within a constructor function the ‘this’ keyword references the new object being created -  so a basic constructor function might be:

function Person(name, age) {
  this.name = name;
  this.age = age;
  this.toString = function() {
    return this.name + " is " + age + " years old.";
  };
}

var john = new Person("John Galt", 50);

console.log(john.toString());

Note that by convention the name of a constructor function is always written in Pascal Case (the first letter of each word is capital). This is to distinguish between constructor functions and other functions. It is important that constructor functions be called with the ‘new’ keyword and that not constructor functions are not.

There are two problems with the pattern constructor function pattern shown above:

  1. It makes inheritance difficult
  2. The toString() function is redefined for each new object created by the Person constructor. This is sub-optimal because the function should be shared between all of the instances of the Person type.

Constructor Functions with a Prototype

JavaScript functions have a special property called prototype. When an object is created by calling a JavaScript constructor all of the properties of the constructor’s prototype become available to the new object. In this way many Person objects can be created that can access the same prototype. An improved version of the above example can be written:

function Person(name, age) {
  this.name = name;
  this.age = age;
}

Person.prototype = {
  toString: function() {
    return this.name + " is " + this.age + " years old.";
  }
};

var john = new Person("John Galt", 50);

console.log(john.toString());

In this version a single instance of the toString() function will now be shared between all Person objects.

Private Members

The short version is: there aren’t any. If a variable is defined, with the var keyword, within the constructor function then its scope is that function. Other functions defined within the constructor function will be able to access the private variable, but anything defined outside the constructor (such as functions on the prototype property) won’t have access to the private variable. Any variables defined on the constructor are automatically public. Some people solve this problem by prefixing properties with an underscore and then not calling those properties by convention.

function Person(name, age) {
  this.name = name;
  this.age = age;
}

Person.prototype = {
  _getName: function() {
    return this.name;
  },
  toString: function() {
    return this._getName() + " is " + this.age + " years old.";
  }
};

var john = new Person("John Galt", 50);

console.log(john.toString());

Note that the _getName() function is only private by convention – it is in fact a public function.

Functional Object Construction

Because of the weirdness involved in using constructor functions some JavaScript developers prefer to eschew them completely. They theorize that it is better to work with JavaScript’s functional nature than to try and force it to behave like a traditional class-oriented language. When using the functional approach objects are created by returning them from a factory function. An excellent side effect of this pattern is that variables defined with the factory function are accessible to the new object (due to closure) but are inaccessible from anywhere else. The Person example implemented using the functional object construction pattern is:

var personFactory = function(name, age) {
  var privateVar = 7;
  return {
    toString: function() {
      return name + " is " + age * privateVar / privateVar + " years old.";
    }
  };
};

var john2 = personFactory("John Lennon", 40);
console.log(john2.toString());

Note that the ‘new’ keyword is not used for this pattern, and that the toString() function has access to the name, age and privateVar variables because of closure.

This pattern can be extended to provide inheritance and, unlike the constructor function pattern, it supports private variables. However, when working with JavaScript code bases you will find that the constructor function is more common – probably because it is a better approximation of mainstream class oriented languages like C# and Java.

Inheritance

Both of the above patterns can support inheritance but for now, favour composition over inheritance.

Summary

When JavaScript code exceeds simple browser automation object orientation can provide a powerful paradigm for controlling complexity. Both of the patterns presented in this article work – the choice is a matter of style. Only one question still remains; who is John Galt?

JavaScript Class Patterns Feb 06

To write object-oriented programs we need objects, and likely lots of them.

JavaScript makes it easy to create objects:

var liam = {
  name: "Liam",
  age: Number.MAX_VALUE
};

But JavaScript does not provide an easy way to create similar objects. Most object-oriented languages include the idea of a class, which is a template for creating objects of the same type. From one class many similar objects can be instantiated.

cookie cutter

Many patterns have been proposed to address the absence of a class concept in JavaScript. This post will compare and contrast the most significant of them.

Simple Constructor Functions

Classes may be missing but JavaScript does support special constructor functions. By prefixing a call to a constructor function with the ‘new’ keyword we can tell the JavaScript runtime that we want the function to behave like a constructor and instantiate a new object containing the members defined by that function. Within a constructor function the ‘this’ keyword references the new object being created -  so a basic constructor function might be:

function Person(name, age) {
  this.name = name;
  this.age = age;
  this.toString = function() {
    return this.name + " is " + age + " years old.";
  };
}

var john = new Person("John Galt", 50);

console.log(john.toString());

Note that by convention the name of a constructor function is always written in Pascal Case (the first letter of each word is capital). This is to distinguish between constructor functions and other functions. It is important that constructor functions be called with the ‘new’ keyword and that not constructor functions are not.

There are two problems with the pattern constructor function pattern shown above:

  1. It makes inheritance difficult
  2. The toString() function is redefined for each new object created by the Person constructor. This is sub-optimal because the function should be shared between all of the instances of the Person type.

Constructor Functions with a Prototype

JavaScript functions have a special property called prototype. When an object is created by calling a JavaScript constructor all of the properties of the constructor’s prototype become available to the new object. In this way many Person objects can be created that can access the same prototype. An improved version of the above example can be written:

function Person(name, age) {
  this.name = name;
  this.age = age;
}

Person.prototype = {
  toString: function() {
    return this.name + " is " + this.age + " years old.";
  }
};

var john = new Person("John Galt", 50);

console.log(john.toString());

In this version a single instance of the toString() function will now be shared between all Person objects.

Private Members

The short version is: there aren’t any. If a variable is defined, with the var keyword, within the constructor function then its scope is that function. Other functions defined within the constructor function will be able to access the private variable, but anything defined outside the constructor (such as functions on the prototype property) won’t have access to the private variable. Any variables defined on the constructor are automatically public. Some people solve this problem by prefixing properties with an underscore and then not calling those properties by convention.

function Person(name, age) {
  this.name = name;
  this.age = age;
}

Person.prototype = {
  _getName: function() {
    return this.name;
  },
  toString: function() {
    return this._getName() + " is " + this.age + " years old.";
  }
};

var john = new Person("John Galt", 50);

console.log(john.toString());

Note that the _getName() function is only private by convention – it is in fact a public function.

Functional Object Construction

Because of the weirdness involved in using constructor functions some JavaScript developers prefer to eschew them completely. They theorize that it is better to work with JavaScript’s functional nature than to try and force it to behave like a traditional class-oriented language. When using the functional approach objects are created by returning them from a factory function. An excellent side effect of this pattern is that variables defined with the factory function are accessible to the new object (due to closure) but are inaccessible from anywhere else. The Person example implemented using the functional object construction pattern is:

var john = new Person("John Galt", 50);
console.log(john.toString());

var personFactory = function(name, age) {
  var privateVar = 7;
  return {
    toString: function() {
      return name + " is " + age * privateVar / privateVar + " years old.";
    }
  };
};

var john2 = personFactory("John Lennon", 40);
console.log(john2.toString());

Note that the ‘new’ keyword is not used for this pattern, and that the toString() function has access to the name, age and privateVar variables because of closure.

This pattern can be extended to provide inheritance and, unlike the constructor function pattern, it supports private variables. However, when working with JavaScript code bases you will find that the constructor function is more common – probably because it is a better approximation of mainstream class oriented languages like C# and Java.

Inheritance

Both of the above patterns can support inheritance but for now, favour composition over inheritance.

Summary

When JavaScript code exceeds simple browser automation object orientation can provide a powerful paradigm for controlling complexity. Both of the patterns presented in this article work – the choice is a matter of style. Only one question still remains; who is John Galt?

Stoicism Feb 01

image Recently I have been reading about the ancient Greco-Roman philosophy Stoicism, which I encountered via Derek Sivers, Tim Ferriss and my reading of the New England transcendentalists.

The book I read is called A Guide to the Good Life: The Ancient Art of Stoic Joy by William B. Irvine. I liked it a lot, and I don’t want to lose what I have learnt, so I prepared the cheatsheet below.

stoicism_cheat_sheet

The Fast Way to Rebuild a Computer – Ninite.com Feb 01

image Dear Future Me,

The next time you need to repave a Windows computer the link that you can never remember is ninite.com.

Ninite is an online service that lets you select the free tools that they like to have on their computer (Firefox, 7-zip, notepad++, skype etc) and builds a custom installer that will install them all. It will save you hours.

K.

Thanks.

Bye.

image

Investigating Strategies For Functional Decomposition Jan 26

Introducing Functional Decomposition

Before I begin I must apologise. I think I am using the term ‘functional decomposition’ loosely, and probably incorrectly. For the purpose of this article I use functional decomposition to mean the recursive splitting of a large problem into increasingly smaller ones, so that the one large problem may be solved by solving a set of smaller problems.

image

The justification for functional decomposition is that the decomposed problem is more easily solved. As software developers we recognise that the smaller pieces are more easily tested, since they do less and are more cohesive. Functional decomposition is important to all scientific pursuits. Once we understand natural selection we can start to look for humanities ancestral species, once we understand the big bang we can trace our expanding universe back to its origin. Isaac Newton acknowledged the compositional nature of his scientific achievements:

If I have seen further than others, it is by standing upon the shoulders of giants

 

The Two Strategies For Functional Decomposition of Computer Programs

Private Methods

rabbit_hole When I was working on my undergraduate degree I was taught to functionally decompose problems by using private methods. Consider the problem of painting a house. The obvious solution is to solve the problem as a single unit:

public void PaintAHouse()
{
	// all the things required to paint a house
	...
}

We decompose the problem by breaking it into parts:

public void PaintAHouse()
{
    PaintUndercoat();
    PaintTopcoat();
}

private void PaintUndercoat()
{
    // everything required to paint the undercoat
}

private void PaintTopcoat()
{
    // everything required to paint the topcoat
}

The problem can be recursively decomposed until a sufficiently granular level of detail is reached:

public void PaintAHouse()
{
    PaintUndercoat();
    PaintTopcoat();
}

private void PaintUndercoat()
{
    prepareSurface();
    fetchUndercoat();
    paintUndercoat();
}

private void PaintTopcoat()
{
    fetchPaint();
    paintTopcoat();
}

According to Wikipedia, at least one computer programmer has referred to this process as “the art of subroutining”.

The practical issues that I have encountered when using private methods for decomposition are:

  1. To preserve the top level API all of the steps must be private. This means that they can’t easily be tested.
  2. The private methods often have little cohesion except that they form part of the same solution.

Decomposing to Classes

The alternative is to decompose large problems into multiple classes, effectively using a class instead of each private method. The API delegates to related classes, so the API is not polluted by the sub-steps of the problem, and the steps can be easily tested because they are each in their own highly cohesive class. Additionally, I think that this technique facilitates better adherence to the Single Responsibility Principle, since each class can be decomposed until it has precisely one responsibility. Revisiting my previous example using class composition:

public class HousePainter
{
    private undercoatPainter = new UndercoatPainter();
    private topcoatPainter = new TopcoatPainter();

    public void PaintAHouse()
    {
        undercoatPainter.Paint();
        topcoatPainter.Paint();
    }
}

Summary

When decomposing a problem there is more than one way to represent the sub-problems. Using private methods keeps the logic in one place and prevents a proliferation of classes (thereby following the four rules of simple design) but the class decomposition is more easily testable and more compatible with the Single Responsibility Principle.

Code Camp Oz 2010 Nov 21

Each year for the last seven Wagga Wagga hosts the annual Code Camp Oz. It is the largest community .NET conference in Australia.

For reasons I don’t understand the organisers choose to hold ccoz in Wagga; a location that is inconvenient to everyone. My preferred technique to get there is to fly to Canberra and drive a hire car to Wagga. This year I took advantage of some time in Canberra to catch up with a friend and then work on my presentation, before heading to Wagga Friday night.

IMG_7131 Aaron Powell kicked things off Saturday morning with a flying tour of .NET open source CMS platforms. The day was dominated by marathon efforts from Omar Besiso and Steven Nagy.

First Sunday morning was Alex Mackey. The presentation was enjoyable, but the message was depressing. HTML 5 is not going to make my job easier.

Pizza arrived early, bumping my session to 1pm. I had already determined that I had to leave at 2pm to get the hire car back in time so the new schedule didn’t leave a lot of margin. I spoke about BDD with Story Q. There were a lot of good questions and discussion so hopefully some people might get some ideas from it.

IMG_7131 IMG_7132 IMG_7133 IMG_7134 IMG_7135 IMG_7136 IMG_7137 IMG_7138 IMG_7139 IMG_7140 IMG_7141 IMG_7142

Windows Phone 7 Startup Camp Nov 15

IMAG0049 I have mentioned before that I own an Android phone. But I can drive a car and still be interested in motor bikes – and so it was that I spend my weekend at the Brisbane Windows Phone 7 Startup Camp.

The event schizophrenically mixed the startup camp idea (create a new business in a weekend) with the new Windows Phone 7 technology. Over the weekend 7 teams built 7 apps, forming the basis of 7 new businesses. It doesn’t get much more biblical than that.

IMAG0050 Things began on Friday, with an optional training day delivered by Nick Randolph. Since I’m a web guy with no phone or silverlight experience I made sure to attend the training and try to learn something. Nick did his best to try and teach us web guys, who don’t know our StackPanel from our xaml.

Saturday was focused on choosing an idea and building something. My team, Paul Mckee, Tod Thomson and me, built a TV Guide application for the Windows Phone 7. We laughed, we cried, we coded long into the afternoon. Then we went to the pub.

Sunday morning the teams started with renewed enthusiasm and redoubled efforts. We finished our applications and then turned our attention to crafting sophisticated presentations to pitch our products to the judging panel. After the pitches the judges chose a worthy winner – then we went to the pub.

THE TV GUIDE