Sunday, April 22, 2012

Specifications in Javascript

I have learned to love the concept of specifications, derived from the Specification Pattern. While the way that I have used them is really just a subset of the actual pattern – I have found it very easy to introduce into my existing code.

Basically, we want to separate boolean based logic from the domain object so that it can be used by others, and changed independently.  For example given a Person object,


We may have business rules about their name like hasName and isAge.


these examples show how we can easily reuse the logic behind hasName and isAge. Here is what the functions actually look like.


It is worth noting that hasName doesn’t actually have to return a function – because the specification itself doesn’t have any arguments (isAge does). For consistency, I decided that all specifications should wrap a function. The actual specification takes the arguments, and the inner function takes the object to be tested.

This actually only gets us to the point that we can do things like this


not things like


if we have gone through all the effort to create the specification, we might as well make it available right on the domain object. In a dynamic language like javascript that is relatively easy and highly reusable.



I am debating moving specifications into the prototype stack. They aren’t very usable in the typical context of prototype (inheritance), but it would eliminate the need for passing specifications to SpecificationInjector because it would just look for it on the object that was passed to it.

MVVM and Dependencies

I am still learning Model-View-ViewModel via KnockoutJS. One concern I find myself continually coming back to is handling dependency. Let me illustrate with a simple example.

   1:  function PersonViewModel(personModel){
   2:      this.Name = ko.observable(personModel.Name);
   3:  }

Here we have created a simple view model for a person – not concerned with dependencies just yet… but now we want to be able to save a person – so we end up with…

   1:  function PersonViewModel(personModel){
   2:      this.Name = ko.observable(personModel.Name);
   3: = function(){
   4:          $.ajax(...);
   5:      };
   6:  }

This is a point of contention. My sniffer goes off about Single Responsibility, it is very possible that at some point we may change how we access the server for Person, and Person should be unaffected (ie. url change, moving some arguments into the url/ query string, switching from rest to node.js, or not hit the server at all, like local storage). So lets get some separation of concerns in here.

   1:  function PersonViewModel(personModel, personDataAccessObject){
   2:      var self = this;
   3:      self.Name = ko.observable(personModel.Name);
   4: = function(){
   6:      };
   7:  }

Alright, so this is looking good… until we start using it…

   1:  function ContactManagerViewModel(){
   2:      var self = this;
   3:      self.contacts = ko.observableArray([]);
   4:      self.createContact = function(){
   5:          self.contacts.push(new PersonViewModel({
   6:              Name: 'Sally'
   7:          }));
   8:      };
   9:  }

This is what we would like to see – note the simple call to construct a PersonViewModel – but this is going to fail miserably when we try to save (b/c we never passed in the personDataAccessObject). Surely we could just pass it in, but the coupling can get out of control as everything it needs, we need in our constructor, and we have to pass to it, and anytime its constructor changes so do we. Been there, done that, ain’t going back.


  1. Global Namespace we can put personDataAccessObject in the global namespace so that any other class can get to it, it also provides a way for a consumer to change that dependency without effecting other code. What I don’ like is that because it is global – if there were multiple instances of our contactManager, it would be very difficult to allow them to use different implementations of personDataAccessObject because they are both pointing to the same global reference. (Note while on the surface personDataAccesssObject might not seem like a good example, imagine one instance is for preview and you don’t want to actually save data)

  2. Closure this style is going to be harder to explain, but basically the entire app (all the ViewModels, etc.) live in one closure so that they can share variables. This giant closure would have one public method exposed which returns the namespace so that you could put it wherever you want. Then you could have two of these namespaces, and can override the implementation of personDataAccessObject for just one of them. I prefer to keep my js classes encapsulated to one js file as this keeps me honest in terms of coupling. The equivalent of this in C# would be to use inner classes – which is rarely the right solution.

  3. Coupling to Parent  for our PersonViewModel, instead of taking a personDataAccessObject, we would take a ContactManagerViewModel and would reference it as parent. ContactManagerViewModel would have the responsibility of having a way for us to save. I don’t feel like this really solves anything. We still have coupling between the two and we still need to pass in extra stuff to PersonViewModel. Where I guess would buy us something is when PersonViewModel requires 5 dependencies, it could be just one.

  4. Factory Pattern in forcing myself to think about how I would solve this if I wasn’t in the UI – I land at Factory Pattern. The idea is that we would have one or more factories that are responsible for depdencies. They would encapsulate any instantiation logic so that there is one place that knows how to properly instantiate things, and would expose methods for things like personDataAccessObject.

Ironically, Factory Pattern is a little of the other 3 (but arguably the right little). Its constructor would live in the global namespace so that anyone can create one. It will have its own closure maintaining instances, etc. that is is not global like #2. And we will have to pass it to our children, but arguably only it, like #3.

So here is the factory

   1:  function ContactManagerFactory(){
   2:      this.getPersonDataAccessObject = function(){
   3:          return {
   4:              save : function(person){
   5:                  $.ajax(...);
   6:              }
   7:          };
   8:      }
   9:  }

we can new one up and override things at will (have as many separate instances as we want).

   2:  var factory = new ContactManagerFactory();
   3:  factory.getPersonDataAccessObject = function(){
   4:      return {
   5:          save : function(){
   6:              // do nothing - this is  a preview
   7:          }
   8:      };
   9:  }

we can then pass it around like so

   1:  function ContactManagerViewModel(factory){
   2:      var self = this;
   3:      self.contacts = ko.observableArray([]);
   4:      self.createContact = function(){
   5:          self.contacts.push(factory.newPerson({
   6:              Name: 'Sally'
   7:          });
   8:      };
   9:  }

notice the need for a newPerson method (which needs to pass a factory to PersonViewModel and so happens to be a factory – see where this is going…)

   1:  function ContactManagerFactory(){
   2:      var self = this;
   3:      self.getPersonDataAccessObject = function(){
   4:          return {
   5:              save : function(person){
   6:                  $.ajax(...);
   7:              }
   8:          };
   9:      };
  11:      self.newPerson = function(personModel){
  12:          return new PersonViewModel(personModel, self);
  13:      }
  14:  }


   1:  function PersonViewModel(personModel, factory){
   2:      var self = this;
   3:      self.Name = ko.observable(personModel.Name);
   4: = function(){
   5:          factory.getGersonDataAccessObject().save(self);
   6:      };
   7:  }

In closing, there are things I don’t like – (super factory object) but it’s the closest I was able to come up with, and the only thing I could come up with that I could stomach.

Saturday, April 21, 2012

Continuous Integration for Javascript

I have been on a journey to introduce Javascript into our Continuous Integration and Test Driven Development eco-system.

For so long, Javascript has been treated like the ugly duckling, but with budding technologies like Knockout.js and Node.js, javascript is becoming a critical component of most systems.

The team at work decided to move forward with QUnit for the testing framework. I found a great link that showed how to get up and running with QUnit and PhantomJs here.

I ended up with the following files (from jQuery and the above blog post). Note I did not use the same name for my phantom-qunit-testrunner.js as the author of the blog post. 

Update – I am now using the run-qunit.js from phantomJS instead of phantom-qunit-testrunner.js from the above blog post.


I was then able to run phantomJs



The blog post author was going after Continuous testing, which is very cool – but not what I need.

There is a lot to consider in the context of automation for Continious Integration. Generally, I don’t need my own html file. I just need the tests. So here goes the first feature.

When a js file (ie. coolplugin.js) is discovered during continuous integration, we should look for an associated test file (ie. coolplugin.test.js), if one is found, then we should generate the required qunit html, run the html though PhantomJS. The file should be unique (ie. coolplugin.test.html), and should not be deleted so that it can inspected for a failing test.

There will be times where I do need to provide my own dom elements, and therefore provide my own html. so here goes another feature.

When a js file (ie. coolplugin.js) is discovered during continuous integration, we should first look for an associated html file (ie. coolplugin.test.html), if one is found, then we should run the html though PhantomJS.

For this I created a simple executable which will perform the above tasks. (it is currently available on our internal svn – if you want it just leave a comment and I can put it in git hub).

Then I tied it all together with NAnt.


I am new to NAnt so I am sure I did several things wrong but its working….

Tests Passed


Tests Failed


Whats next? Prototype to production – and continuous testing for local development.

jQuery plugins and html data driven options

Wouldn’t it be nice if you could write a jquery plugin that takes options from the plugin, from the dom, or from defaults….?

But who wants to own that code?

This used to be a pain a few years ago, but html5 and have made this quite easy.

Monday, April 16, 2012

JSHint or JSLint

Heard the buzz about JSHint?

I too am not a big fan of an opinionated code quality tool, but one of the main reasons I am hearing of people using JSHint is that doesn’t force you to declare your variables at the top of a function.

While it is really annoying to have to do this, I remembered in reading Javascript the Good Parts that it is best practice – I just couldn’t remember why.

Then I ran across this post which provides a snippet of why.

var name = "Dan";

function getName(){
    var name = "Paul";
    return name;
var newName = getName();

You would expect that console.log(name) would print “Dan” but instead it will print ‘undefined.’ This is because the variable name is scoped to the function and though the value gets set later, it is declared and scoped to the entire function.

If your going to allow this – you need to understand the ramifications.

The counter argument is that declaring variables at the top is noisy and unintuitive, especially in loops.