Liam McLennan

March 2011 Entries

Mocking Extension Methods on NHibernate.ISession

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

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

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

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.