Design, Build and Release

Ramblings of IainJMitchell on C#, Javascript and Software Craftsmanship

Archive for the ‘Uncategorized’ Category

Constructor Function v Prototype in Javascript

leave a comment

There are two main mechanisms for creating objects in Javascript, these are known as Constructor Function and Prototype. In this post I will run through an example of each and explain my preference.

Lets say we want to create a Cat object, this has to be constructed with the cats name (e.g. Terry) and it also needs a single method called sayHello() which will reveal the cats name. Our orchestrating code would look something like this:

var aCat = new Cat("Terry");
alert(aCat.sayHello()); 
//alerts "Meow! My name is Terry"

If we coded this using the Constructor Function approach, it would look something like this:

var Cat = function(name){
  function sayHello(){
    return "Meow! My name is " + name;
  }
  
  return {
    sayHello: sayHello
  };
};

The code creates a new function assigned to the variable Cat, so every time a new Cat is created this function is executed. This function also has a parameter ‘name’ which will be the argument passed into the constructor.

Within the closure (scope of the function) is our sayHello() method, this is only revealed publicly on an instance of Cat because it is included in the associative array that is returned from the constructor function (lines 6 to 8).

You may notice that the ‘name’ parameter of the constructor is also being used within the sayHello() function, this is a consequence of the function being defined within the closure of the constructor function. Many find this odd and it often confuses people when they are new to Javascript, but it is a very powerful technique which is especially when dealing with the complex nature of context.

So, what would the solution look like using the alternative prototype approach?

var Cat = function(name){
  this.name = name;
};

Cat.prototype.sayHello = function(){
    return "Meow! My name is " + this.name;
};

Again, in this example the base object is a function that takes an argument of ‘name’, the difference here is that we have to assign name to this (the result of the executed function).

The public method sayHello() has to be assigned to a special area on the Object definition called the prototype, any functions attached added to this will be available to all new instances created. A big advantage of using the prototype is that only one definition of this method will exist in memory, regardless of how many Cats we create.

Because the sayHello() method is defined outside the closure of the base object function, the only way it can access the name property is by using the this keyword. Unfortunately this also means that the name field is available outside the object instance, otherwise known as a public field! This means I could do the following with the prototype code:

var terry = new Cat("Terry");
terry.name = "Roy"
alert(aCat.sayHello()); 
//alerts "Meow! My name is Roy" oops!

I’m a strong advocate of not revealing object state, so I very rarely use the prototype approach. Some suggest that you can get around it by having a naming convention for fields you should not touch externally, but to me this seems brittle and open to abuse, especially if third parties have to consume your code.

Some people like to use prototype as it also supports Object inheritance, but I would argue that sharing behaviour through aggregation is a much better approach than inheritance.

Constructor Function also has the advantage of allowing you to define private functions and internal composite objects, an approach also used in the excellent Javascript module pattern.

Written by IainJMitchell

January 31st, 2013 at 10:15 am

Posted in Uncategorized

Tagged with ,

Manchester Codejo

leave a comment

I have been involved in the setting up of a new monthly coding event in Manchester called Manchester Codejo. The first event is taking place on Tuesday 23rd October 2012 and is being hosted at the new TechHub Manchester offices (who have also kindly offered to sponsor the event).

Follow this link for further information and registration.

Written by IainJMitchell

September 30th, 2012 at 9:02 pm

Posted in Uncategorized

Tagged with ,

A tour of our Kanban board

leave a comment

In this post I’m going to give a quick run through the Kanban board that my team uses at LateRooms.com. This is not a ‘thou shalt do it this way’ article, it is intended to demonstrate a working board and explain its structure. Also, I must stress that this is the current state of the board at the time of this post was written, so it has probably evolved again by now!

The board

The board is split into 4 silos:

  • Backlog -> For the Business Analyst (BA) to add and prioritise tickets
  • DEV -> contains the queue (pending) and work in progress (WIP) columns for development work.
  • QA -> contains pending and WIP columns for QA-ing (AKA testing)
  • RELEASE -> has a column for pending release and a column for released (done)

When a ticket is ready for development, the BA will place the task into the DEV pending column. This is now available to be pulled through development and QA-ing until the ticket is eventually released onto the live estate. Tickets are not allowed to go back, so if an issue is discovered in QA-ing the ticket will remain in the QA until the issue is resolved.

The board has an expedite swim lane for the tracking of high priority tasks. Any urgent tickets can be placed and pulled along this row until they are eventually released in an emergency fix. There is no pending DEV column in this swim lane, as tasks critical enough to be expedite should not sit in a pending DEV column.

The other features of the board (labelled 1 to 7) are:

  1. Legend – This shows the types of cards (by colour) that can be on the board, these include New features, Tech debt, Defects, Investigations (support) and External Issues (e.g. new servers). The purpose of this is to clearly visualise the type of work that is being processed
  2. Limits – Each pending and work in progress column has a limit to control the amount of work that can be taken on. These limits are set based on resource levels and other bottlenecks, and are intended to encourage the PULLING of work when capacity exists rather than continuing to force more work onto a bottleneck.
  3. Avatar – Each team member has ONE avatar to place on the item they are on, this tells other team members that this card is being worked upon and should be progressing. As we pair on most development, there will often be more than one avatar on each Dev task.
  4. Arrows – Indicate movement of tasks since the last standup, again this is part of the visualisation of the process. These cards are often ignored at the standup, as we want to focus on the items that are not progressing, such as…
  5. Blockers – We want to minimise blockers as they cause more bottlenecks in the system, so we clearly indicate these items with blocked avatar. An additional requirement to blocking a card is to add the details of WHO and WHY the item is unable to proceed.
  6. Waste – Tasks can be abandoned at any stage in the process, we collect these and review at the weekly retrospective.
  7. Continuous Improvements – Also, at the weekly retrospective we decide upon three improvement points that we want to tackle for the following week. These are summarised on the board and recalled at the beginning of the morning standup, if we fail to make any progress on an improvement then it may be rolled over to the next week.

Written by IainJMitchell

August 22nd, 2012 at 1:00 pm

Posted in Uncategorized

Tagged with , ,

A quick introduction to nodejs

leave a comment

Introduction

nodejs is here, it’s going to save the world, long live Javascript!
Oh really?
As Chuck D says “Don’t believe the Hype”, however I’ve been using nodejs for a year or so and I quite like it.

Server side Javascript?

Well it is the simplest definition, but not 100% accurate. Yes, nodejs code is written in Javascript (the clue is in the js part of the name), but it’s actually defined as Event Driven, Asynchronous IO.

  1. Event Driven – eventing is built into the framework, which allows us to pass messages/commands in a nice OO friendly manor (tell don’t ask)
  2. Asynchronous IO – input and output does not block, which means no need for complex thread management

What do I need?

nodejs runs on Windows and Linux (I’d recommend the latter), it can be downloaded from here or directly from the git repository.

Fisherprice, my first node app

require('http')
	.createServer(function (request, response) { 
		response.writeHead(200, {'Content-Type': 'text/plain'});
		response.end('Hello World');
	})
	.listen(1337);

console.log('Server running');

To execute the code we execute node from the command line, using the file name as an argument, e.g.
node helloWorld.js.

This code creates an app that is hosted at http://localhost:1337, when this address is hit the response will be a HTTP 200 (success) with the text ‘Hello World’. Pretty simple and no need for hosting in a separate web server*.

We can also rewrite this example to work with net.tcp:

require('net')
	.createServer(function (socket) {
		socket.write('helloWorld')
	})
	.listen(1330);

It’s all about the modules

You probably noticed the require keyword in the above examples, which is a request to load up a named module. This is possible because nodejs implements the CommonJS standard of defining and loading modules.

This allows us to define our own modules, like so:

var helloWorlder = function(){
	return 'hello world';
};

exports.helloWorlder = helloWorlder;

The exports object allows us to define the API of our module, in this case this is just a simple ‘hello World’ function. If this is saved in a file named aModule.js, then we can utilise this in another node application like so:

var module = require('./aModule.js');

console.log(module.helloWorlder());

Open source == Communism?

Of course, it would be dull world if we kept our node modules to ourselves. nodejs is all about open source and sharing our code, and this is where Node Package Manager (NPM) comes in.

NPM allows you to consume open source node modules and also submit your own. After installation NPM allows you to install modules at the command line, such as the following example for underscore:
NPM install underscore

After successfully running this command, you can then use underscore in your node app:

_ = require('underscore');
var collection = [1,2];
console.log(_.first(collection));

Good practice -> node modules differ from the large client side libraries (e.g. jQuery, Mootools etc), they tend to be smaller and focussed on one particular task.

Eventing

This often overlooked feature of node is implemented through the EventEmitter class, which allows code to publish messages/commands to other subscribing sections of code. Here is an example of a direct use of the event emitter:

var EventEmitter = require('events').EventEmitter;
var publisher = new EventEmitter();

publisher.on('stuff', function(){
	console.log('stuff event fired');
});

publisher.on('stuff', function(){
	console.log('other stuff event fired');
});

publisher.emit('stuff');

When this code is executed the emit call will output the following to the console:
stuff event fired
other stuff event fired

Classes can also inherit from the EventEmitter, allowing them to have their own dedicated subscribers that they can emit to (see my node shopping cart kata for an event driven node solution).

Lessons Learnt

  • Unit Testing – There is a node port of Jasmine, but I’d recommend Vows, which is an asynchronous unit testing framework designed for use with node
  • Coffeescript – This is a language that compiles down into Javascript, it gives you a more ruby like syntax and much easier construction of classes and inheritance. Although the outputted Javascript is a bit too verbose for client side code, it is great for node. More details here.
  • MVCExpress is a lightweight MVC framework for node (think more Sinatra/Nancy rather than ASP.NET MVC).
  • DevelopmentNodeMon can be used to watch files in a directory and restart your node application if they change.

Other useful links

Github repository containing the examples from this post.
Github repository of the shopping kata in nodejs.
Introduction to nodeJs by the creator Ryan Dahl.
@nodejs
@ryah

* Okay, it probably is a good idea to host behind a web server for web facing services, many leading web servers now have support for nodejs processes.

Written by IainJMitchell

May 18th, 2012 at 12:32 pm

Posted in Uncategorized

Tagged with , , ,