Liam McLennan

March 2010 Entries

Syntax Highlighting for Gherkin (Cucumber Language)

SyntaxHighlighter is the de facto standard for syntax highlighting on the web. I am currently working on a tool for publishing BDD specifications on the web and I want syntax highlighting. Unfortunately, SyntaxHighlighter does not support Gherkin, the language Cucumber and SpecFlow use to define BDD specifications. Writing new language parsers for SyntaxHighlighter is very easy, so I implemented one for Gherkin. Here is what a syntax highlighted Gherkin file looks like:

# A comment here

Feature: Some terse yet descriptive text of what is desired
	In order to realize a named business value
	As a explicit system actor
	I want to gain some beneficial outcome which furthers the goal

@secretlabel
Scenario: Some determinable business situation
	Given some precondition
	And some other precondition
	When some action by the actor
	And some other action
	And yet another action
	Then some testable outcome is achieved
	And something else we can check happens too

Like all SyntaxHighlighter brushes to use this one you need to install the brush (shBrushGherkin.js). I have also used a custom theme to get it just the way I wanted it (shThemeGherkin.css). If you would like to use my Gherkin brush you may download the code and example page.

  • Share This Post:
  • Share on Twitter
  • Share on Facebook
  • Share on Technorati

New Company Website

For a long time now my company website has been showing its age. It was a dot net nuke monstrosity.

Today I have deployed a new website for my company. I hope that it reflects my commitment to quality and minimalism.

Please have a look and let me know what you think.

  • Share This Post:
  • Share on Twitter
  • Share on Facebook
  • Share on Technorati
  • Share This Post:
  • Share on Twitter
  • Share on Facebook
  • Share on Technorati

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.

  • Share This Post:
  • Share on Twitter
  • Share on Facebook
  • Share on Technorati

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
  • Share This Post:
  • Share on Twitter
  • Share on Facebook
  • Share on Technorati

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 configuring 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;
     }
 }
  • Share This Post:
  • Share on Twitter
  • Share on Facebook
  • Share on Technorati

Software Craftsman Pilgrimage Comes Together

Last week on Software Craftsman Pilgrimage I was trying to organise where I will be travelling, and the companies I will be pairing with.

I now have a confirmed itinerary.

9 - 11th April Alt.NET Seattle
12th April Craftsman visit with Didit (Long Island)
13th April rest day :)
14th April Craftsman visit with Obtiva (Chicago)
15th – 16th April Craftsman visit with 8th Light (Chicago)
17th – 18th April Seattle Code Camp

I am looking forward to all of my visits and talking to all the smart people who work there. I will be blogging my progress and hopefully shooting some video.

If you are in Seattle, New York or Chicago and would like to meet up to chat about craftsmanship, programming, ruby or .NET please email me.

trip

  • Share This Post:
  • Share on Twitter
  • Share on Facebook
  • Share on Technorati

My New BDD Style

I have made a change to my code-based BDD style. I start with a scenario such as:

Pre-Editing

* Given I am a book editor
* And some chapters are locked and some are not
* When I view the list of chapters for editing
* Then I should see some chapters are editable and are not locked
* And I should see some chapters are not editable and are locked

and I implement it using a modified SpecUnit base class as:

[Concern("Chapter Editing")]
    public class when_pre_editing_a_chapter : BaseSpec
    {
        private User i;
        // other context variables

        protected override void Given()
        {
            i_am_a_book_editor();
            some_chapters_are_locked_and_some_are_not();
        }

        protected override void Do()
        {
            i_view_the_list_of_chapters_for_editing();
        }

        private void i_am_a_book_editor()
        {
            i = new UserBuilder().WithUsername("me").WithRole(UserRole.BookEditor).Build();
        }

        private void some_chapters_are_locked_and_some_are_not()
        {
        }

        private void i_view_the_list_of_chapters_for_editing()
        {
        }

        [Observation]
        public void should_see_some_chapters_are_editable_and_are_not_locked()
        {
        }

        [Observation]
        public void should_see_some_chapters_are_not_editable_and_are_locked()
        {
        }
    }

and the output from the specunit report tool is:

Chapter Editing specifications    1 context, 2 specifications

Chapter Editing, when pre editing a chapter    2 specifications
  • should see some chapters are editable and are not locked
  • should see some chapters are not editable and are locked

The intent is to provide a clear mapping from story –> scenarios –> bdd tests.

  • Share This Post:
  • Share on Twitter
  • Share on Facebook
  • Share on Technorati

Changing Platform

seven_samurai From time to time a developer makes a break from their platform of choice (.NET, Java, VB, Access, COBOL) and moves to perceived greener pastures. Zed Shaw did it, jumping from Ruby to Python, and Mike Gunderloy went from .NET to Rails.

But it can be difficult to change platform. My clients don’t come to me looking for  a software developer, they come looking for a .NET developer. This is a tragic side effect of big software companies marketing.

If your village is under attack by bandits, would you turn away the first seven samurai who offered to help because you didn’t like their swords? What matters is how effectively they can defend your village.

You should not tell your carpenter what sort of hammer to use and you should not tell your software developer what platform to use.

  • Share This Post:
  • Share on Twitter
  • Share on Facebook
  • Share on Technorati

Trying to Organise a Software Craftsman Pilgrimage

As I have previously written, I am trying to organise a software craftsman pilgrimage. The idea is to donate some time working with quality developers so that we learn from each other. To be honest I am also trying to be the worst.

“Always be the worst guy in every band
you’re in.” Pat Metheny

I ended up posting a message to both the software craftsmanship group and the Seattle Alt.NET group and I got a good response from both. I have had discussions with people based in: Seattle, New York, Long Island, Austin and Chicago. Over the next week I have to juggle my schedule and confirm the company(s) I will be spending time with, but the good news is it seems that I will not be left hanging.

  • Share This Post:
  • Share on Twitter
  • Share on Facebook
  • Share on Technorati

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, currenlty 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…

  • Share This Post:
  • Share on Twitter
  • Share on Facebook
  • Share on Technorati

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

  • Share This Post:
  • Share on Twitter
  • Share on Facebook
  • Share on Technorati

Handy Javascript array Extensions – contains(…)

This javascript adds a method to javascript arrays that returns a boolean indicating if the supplied object is an element of the array

Array.prototype.contains = function(item) {
    for (var i = 0; i < this.length; i += 1) {
        if (this[i] === item) {
            return true;
        }
    }
    return false;
};

To test

alert([1,1,1,2,2,22,3,4,5,6,7,5,4].contains(2)); // true
alert([1,1,1,2,2,22,3,4,5,6,7,5,4].contains(99)); // false
  • Share This Post:
  • Share on Twitter
  • Share on Facebook
  • Share on Technorati

Sneaky Javascript For Loop Bug

Javascript allows you to declare variables simply by assigning a value to an identify, in the same style as ruby:

myVar = "some text";

Good javascript developers know that this is a bad idea because undeclared variables are assigned to the global object, usually window, making myVar globally visible. So the above code is equivalent to:

window.myVar = "some text";

What I did not realise is that this applies to for loop initialisation as well.

for (i = 0; i < myArray.length; i += 1) {

}

// is equivalent to


for (window.i = 0; window.i < myArray.length; window.i += 1) {

}

Combine this with function calls nested inside of the for loops and you get some very strange behaviour, as the value of i is modified simultaneously by code in different scopes. The moral of the story is to ALWAYS declare javascript variables with the var keyword, even when intialising a for loop.

for (var i = 0; i < myArray.length; i += 1) {

}
  • Share This Post:
  • Share on Twitter
  • Share on Facebook
  • Share on Technorati

Documenting the Success Scenario

Posts like my intro to jQuery client-side templates may appear, at first glance, to add nothing to the existing body of knowledge. However, the trouble that I regularly encounter with technical documentation is that the author tries too hard to be exhaustive. When first approaching a new topic the reader is most interested in the success scenario. Under normal conditions, how would I use this technology? What is the most basic syntax?

A great example of documentation that focuses on the core usage of a technology is Joel Spolsky’s excellent Hg Init. The top level topics are: Subversion Re-education, Ground up Mercurial, Setting up for a Team, Fixing Goofs, Merging and Repository Architecture. These are exactly the things I want to know about as a Hg newbie.

Much as we describe software functionality with user stories, the best introductory documentation is grouped by ‘what is the reader trying to do’, instead of alphabetical or chronological groupings. Once the reader has a working knowledge of the topic then exhaustive reference documentation becomes useful.

  • Share This Post:
  • Share on Twitter
  • Share on Facebook
  • Share on Technorati

jQuery client-side templates with jqote and Asp.Net MVC

Why Use Client-side Javascript Templates?

When building rich internet applications you often need to construct html on the client. I am going to demonstrate how to construct DOM elements using the jqote jQuery plugin (2.0.0).

The naive approach to client-side html generation is to embed html inside javascript like:

var text = 'Some text';
$('body').append($('<div id="content>' + text + '</div>"'));

This approach fails as the complexity of the html increases. It is also a clear separation of concerns violation to mix html (presentation) with script (interaction).

Javascript templates provide a way to dynamically build html on the client while storing the dynamic html with the rest of the presentation markup. Additionally javascript templates provide MVC-like separation of concerns.

Dynamically Building a Table with a Client-side Javascript Template

Suppose you want a web page that allows the user to build a table of people. For each person the user can enter their name and age. First we need a form to collect the values, and we need some jQuery magic to cancel the form post:

<form id="people_input">
        <label for="name">Name: </label><input type="text" name="name" /><br />
        <label for="age">Age: </label><input type="text" name="age" /><br />
        <input type="submit" value="Add" />
    </form>

    <script type="text/javascript">

        $(document).ready(function () {

            $('form#people_input').submit(function (e) {
                e.preventDefault();
            });

        });    
    
    </script>

There needs to be a table to display the people, and each time the form is submitted a new row should be added to the table. jqote templates are defined in the html by wrapping the template in a script tag and a CDATA tag. The script tag is necessary to stop the template from being interpreted as part of the page. The CDATA tag is required so that the page remains syntactically valid. Here is my empty table and a template for a row:

<table id="person_table">
        <tr>
            <th>Name</th><th>Age</th>
        </tr>    
    </table>

    <script type="text/html" id="template">
    <![CDATA[
        <tr>
            <td><$= this.name $></td><td><$= this.age $></td>
        </tr>    
    ]]>
    </script>

The default jqote tags use <%= %> syntax which I have replaced with <$= $> to avoid conflict with Asp.Net MVC. Inside of a jqote template ‘this’ refers to the data object used to render the template. Within the jqote tags any javascript is valid since jqote is based on John Resig’s Javascript Micro-Templating.

The final, and most interesting step is to render the template each time the form is submitted and insert the result at the end of the table. Note the second parameter to the jqote() method, which is the character to use for the html nugget syntax.

        $(document).ready(function () {

            $('form#people_input').submit(function (e) {
                var data = { name: $('input[name=name]').val(), age: $('input[name=age]').val() };
                $('table#person_table').append($('#template').jqote(data, '$'));
                e.preventDefault();
            });

        });   

To try out the complete code, grab it from codepaste.net.

  • Share This Post:
  • Share on Twitter
  • Share on Facebook
  • Share on Technorati