Unnamed Refactoring

This post is a message in a bottle. I cast it into the sea in the hope that it will one day return to me, stuffed to the cork with enlightenment. Yesterday I  tweeted,

what is the name of the pattern where you replace a multi-way conditional with an associative array?

I said ‘pattern’ but I meant ‘refactoring’. Anyway, no one replied so I will describe the refactoring here.

Programmers tend to think imperatively, which leads to code such as:

public int GetPopulation(string country)
{
   if (country == "Australia")
   {
       return 22360793;
   } else if (country == "China")
   {
       return 1324655000;
   } else if (country == "Switzerland")
   {
       return 7782900;
   }
   else
   {
       throw new Exception("What ain't no country I ever heard of. They speak English in what?");                    
   }
}

which is horrid. We can write a cleaner version, replacing the multi-way conditional with an associative array, treating the conditional as data:

public int GetPopulation(string country)
{
   if (!Populations.ContainsKey(country))
       throw new Exception("The population of " + country + " could not be found.");

   return Populations[country];
}

private Dictionary<string, int> Populations
{
   get
   {
       return new Dictionary<string, int>
           {
               {"Australia", 22360793},
               {"China", 1324655000},
               {"Switzerland", 7782900}
           };
   }
}

 

Does this refactoring already have a name? Otherwise, I propose

Replace multi-way conditional with associative array


Why’s Poignant Guide To Ruby

According to Wikipedia, “why the lucky stiff was the persona of an anonymous, but prolific writer, cartoonist, musician, artist, and computer programmer”. He looks a bit like Jack Black.

His book, Why’s Poignant Guide to Ruby, is a classic, though it can be hard to find since Why disappeared. If you want to learn the Ruby programming language I highly recommend Why’s Poignant Guide to Ruby. I am including a link here so that others who search for it may find it more easily.


My Latest Hare-Brained Scheme

I have not had a significant side project for a while but I have been working on a product idea. Its an analytics application that analyses twitter data and reports on market sentiment. The target market is companies who want to track trends in consumer sentiment.

My idea is to teach the application to divide relevant tweets into ‘positive’ and ‘negative’ categories. If the input was the set of tweets featuring the word ‘telstra’ the application would find the following tweet:

image 

 

and put it in the ‘negative’ category. Collecting data in this fashion facilitates the creation of graphs such as:

image

which can then be correlated against events, such as a share offer or new product release.

I may go ahead and build this, just because I am a programmer and it amuses me to do so. My concerns are:

  1. There  is no market for this tool
  2. There is a market, but I don’t understand it and have no way to reach it.

NHibernate Error - Expression argument must be of type ICollection

The above error occurred when I executed a linq query using the following expression:

(s) => s.Book.Slug.Equals(bookslug) && ids.Contains(s.Id);

ids in this case is of type IEnumerable<Guid>. As indicated by the error message the fix is to change ids to ICollection<Guid>, then the query executes successfully.


CoffeeScript Test Framework

Tonight the Brisbane Alt.NET group is doing a coding dojo. I am hoping to talk someone into pairing with me to solve the kata in CoffeeScript. CoffeeScript is an awesome language, half javascript, half ruby, that compiles to javascript. To assist with tonight’s dojo I wrote the following micro test framework for CoffeeScript:

<html>
<body>

<div>
	<h2>Test Results:</h2>
	<p class='results' />
</div>
	<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js" type="text/javascript"></script>

<script type="text/coffeescript">

# super simple test framework
test: {
	write: (s) ->
		$('.results').append(s + '<br/>')		
		
	assert: (b, message...) -> 
		test.write(if b then "pass" else "fail: " + message)
		
	tests: []
	
	exec: () ->
		for t in test.tests
			test.write("<br/><b>$t.name</b>")
			t.func()
}

# add some tests
test.tests.push { 
		name: "First Test"
		func: () ->	
			test.assert(true)
	}
	
test.tests.push {
		name: "Another Test" 
		func: () ->
			test.assert(false, "You loose")
	}
	
# run them
test.exec(test.tests)
</script>

<script type="text/javascript" src="coffee-script.js"></script>

</body>
</html>

It’s not the prettiest, but as far as I know it is the only CoffeeScript test framework in existence. Of course, I could just use one of the javascript test frameworks but that would be no fun. To get this example to run you need the coffeescript compiler in the same directory as the page.


A Reusable Builder Class for Javascript Testing

Continuing on my series of builders for C# and Ruby here is the solution in Javascript. This is probably the implementation with which I am least happy. There are several parts that did not seem to fit the language.

This time around I didn’t bother with a testing framework, I just append some values to the page with jQuery. Here is the test code:

var initialiseBuilder = function() {
	var builder = builderConstructor();
	
	builder.configure({
		'Person': function() { return {name: 'Liam', age: 26}},
		'Property': function() { return {street: '127 Creek St', manager: builder.a('Person') }}
	});
	return builder;
};

var print = function(s) {
	$('body').append(s + '<br/>');
};

var build = initialiseBuilder();

// get an object
liam = build.a('Person');
print(liam.name + ' is ' + liam.age);

// get a modified object
liam = build.a('Person', function(person) { person.age = 999; });
print(liam.name + ' is ' + liam.age);

home = build.a('Property');
print(home.street + ' manager: ' + home.manager.name); 

and the implementation:

var builderConstructor = function() {
	var that = {};
	var defaults = {};
	that.configure = function(d) {
		defaults = d;
	};	
	that.a = function(type, modifier) {
		var o = defaults[type]();
		if (modifier) {
			modifier(o);
		}
		return o;
	};	
	return that;
};

I still like javascript’s syntax for anonymous methods, defaults[type]() is much clearer than the Ruby equivalent @defaults[klass].call(). You can see the striking similarity between Ruby hashes and javascript objects. I also prefer modifier(o) to the equivalent Ruby, yield o.


A Reusable Builder Class for Ruby Testing

My last post was about a class for building test data objects in C#. This post describes the same tool, but implemented in Ruby. The C# version was written first but I originally came up with the solution in my head using Ruby, and then I translated it to C#. The Ruby version was easier to write and is easier to use thanks to Ruby’s dynamic nature making generics unnecessary. 

Here are my example domain classes:

class Person
	attr_accessor :name, :age
	
	def initialize(name, age)
		@name = name
		@age = age
	end	
end

class Property
	attr_accessor :street, :manager
	
	def initialize(street, manager)
		@street = street
		@manager = manager
	end
end

and the test class showing what the builder does:

class Test_Builder < Test::Unit::TestCase
	
	def setup
		@build = Builder.new	
		@build.configure({ 
			Property => lambda { Property.new '127 Creek St', @build.a(Person) },
			Person => lambda { Person.new 'Liam', 26 }			
		})
	end
	
	def test_create
		assert_not_nil @build
	end
	
	def test_can_get_a_person
		@person = @build.a(Person)
		assert_not_nil @person
		assert_equal 'Liam', @person.name
		assert_equal 26, @person.age
	end
	
	def test_can_get_a_modified_person
		@person = @build.a Person do |person|
			person.age = 999
		end
		assert_not_nil @person
		assert_equal 'Liam', @person.name
		assert_equal 999, @person.age
	end
	
	def test_can_get_a_different_type_that_depends_on_a_type_that_has_not_been_configured_yet
		@my_place = @build.a(Property)
		assert_not_nil @my_place
		assert_equal '127 Creek St', @my_place.street
		assert_equal @build.a(Person).name, @my_place.manager.name
	end
end

Finally, the implementation of Builder:

class Builder

	# defaults is a hash of Class => creation lambda
	def configure defaults
		@defaults = defaults
	end
	
	def a(klass)
		temp = @defaults[klass].call()
		yield temp if block_given?
		temp
	end

end

A Reusable Builder Class for .NET testing

When writing tests, other than end-to-end integration tests, we often need to construct test data objects. Of course this can be done using the class’s constructor and manually configuring the object, but to get many objects into a valid state soon becomes a large percentage of the testing effort.

After many years of painstakingly creating builders for each of my domain objects I have finally become lazy enough to bother to write a generic, reusable builder class for .NET. To use it you instantiate a instance of the builder and configure it with a builder method for each class you wish it to be able to build. The builder method should require no parameters and should return a new instance of the type in a default, valid state. In other words the builder method should be a Func<TypeToBeBuilt>. The best way to make this clear is with an example. In my application I have the following domain classes that I want to be able to use in my tests:

public class Person
{
  public string Name { get; set; }
  public int Age { get; set; }
  public bool IsAndroid { get; set; }
}

public class Building
{
  public string Street { get; set; }
  public Person Manager { get; set; }
}

The builder for this domain is created like so:

 

build = new Builder();
build.Configure(new Dictionary<Type, Func<object>>
{
    {typeof(Building), () => new Building {Street = "Queen St", Manager = build.A<Person>()}},
    {typeof(Person), () => new Person {Name = "Eugene", Age = 21}}
});

 

Note how Building depends on Person, even though the person builder method is not defined yet. Now in a test I can retrieve a valid object from the builder:

 

var person = build.A<Person>();

 

If I need a class in a customised state I can supply an Action<TypeToBeBuilt> to mutate the object post construction:

var person = build.A<Person>(p => p.Age = 99);

 

The power and efficiency of this approach becomes apparent when your tests require larger and more complex objects than Person and Building. When I get some time I intend to implement the same functionality in Javascript and Ruby. Here is the full source of the Builder class:

 public class Builder
 {
     private Dictionary<Type, Func<object>> defaults;

     public void Configure(Dictionary<Type, Func<object>> defaults)
     {
         this.defaults = defaults;
     }

     public T A<T>()
     {
         if (!defaults.ContainsKey(typeof(T))) throw new ArgumentException("No object of type " + typeof(T).Name + " has been configured with the builder.");
         T o = (T)defaults[typeof(T)]();
         return o;
     }

     public T A<T>(Action<T> customisation)
     {
         T o = A<T>();
         customisation(o);
         return o;
     }
 }

My Message to the Software Craftsmanship Group

This is a message I posted to the software craftsmanship group, looking for a week-long, pairing / skill sharing opportunity in the USA.

I am a journeyman software craftsman, currently living and working in Brisbane Australia. In April I am going to travel to the US to attend Alt.Net Seattle and Seattle codecamp.

In between the two conferences I have five days in which I would like to undertake a craftsmanship mini-apprenticeship, pairing and skill sharing with your company. I do not require any compensation other than the opportunity to assist you and learn from you. Although my
conferences are in Seattle I am happy to travel anywhere in the USA and Canada (excluding Hawaii :) ).

Things I am good at: .NET web development, javascript, creating software that solves problems
Things I am learning: Ruby, Rails, javascript

If you are interested in having me as visiting craftsman from the 12th to the 16th of April please reply on this mailing list or contact me directly.

Liam McLennan

Now I wait…


Handy Javascript array Extensions – distinct()

The following code adds a method to javascript arrays that returns a distinct list of values.

Array.prototype.distinct = function() {
    var derivedArray = [];
    for (var i = 0; i < this.length; i += 1) {
        if (!derivedArray.contains(this[i])) {
            derivedArray.push(this[i])
        }
    }
    return derivedArray;
};

and to demonstrate:

alert([1,1,1,2,2,22,3,4,5,6,7,5,4].distinct().join(','));

This produces 1,2,22,3,4,5,6,7

Note that this implementation of distinct() is dependant upon my implementation of contains.