GitHub LinkedIn RSS
Sunday, June 29, 2014

JavaScript Factory Patterns


Since June has 5 Sundays in it, today I will write a bonus article :) Following our last week's article about Publish and Subscribe Pattern with Postal.js, I'd like to broaden the topic talking about design patterns. The design patterns from the Gang of Four book offer solutions to common problems related to the object-oriented software design. It has been in use for decades and implemented in all server side languages. It's time we use them with JavaScript and start to write some piece of decent code. I'll be writing a series of articles covering all of them. As in the book, we'll be starting with creational patterns and cover both Abstract Factory and Factory Method patterns.

Abstract classes and interfaces enforce consistent interfaces in derived classes. In JavaScript we must ensure this consistency ourselves by making sure that each 'concrete' object has the same interface definition (i.e. properties and methods) as the others.

Abstract Factory Pattern


The Abstract Factory Pattern provides an interface for creating specific factories of dependent objects without specifying their concrete class.  Have a look at the illustration, depicting the pattern using UML.


Observe how Client is only aware of IMotherBoard and ICPU interfaces. The concrete factory responsible for creating the instances implementing these interfaces is also unknown. In JavaScript we don't have interfaces, but it doesn't mean that we cannot use the design pattern. Behold:
function FastCPU() {
    this.performOperation = function() {
        console.log("Operation will perform quickly");
    }
}
function SlowCPU() {
    this.performOperation = function() {
        console.log("Operation will perform slowly");
    }
}

function ExpensiveMotherBoard() {
    this.storeData = function() {
        console.log("There is a lot of RAM to store the data");
    }
}

function CheapMotherBoard() {
    this.storeData = function() {
        console.log("Little RAM. Swap file is used");
    }
}

function HighBudgetMachine() {
    this.getCPU = function() { return new FastCPU(); }
    this.getMotherBoard = function() {
     return new ExpensiveMotherBoard();
    }
}

function LowBudgetMachine() {
    this.getCPU = function() { return new SlowCPU(); }
    this.getMotherBoard = function() {
     return new CheapMotherBoard();
    }
}
All our classes implement the appropriate "ghost" interfaces. Now let's build our client:
function Client() {
 this.assembleMachine = function(factory) {
  var cpu = factory.getCPU(), 
   board = factory.getMotherBoard();
  // test the machine
  cpu.performOperation();
  board.storeData();
 }
}

var client = new Client();
client.assembleMachine(new HighBudgetMachine());
The output of course will be:
Operation will perform quickly
There is a lot of RAM to store the data 

Factory Method Pattern


The Factory Method pattern is a way of creating objects, but letting subclasses decide exactly which class to instantiate. Various subclasses might implement the interface; the Factory Method instantiates the appropriate subclass based on information supplied by the client or extracted from the current state. Please review the illustration below and the involved entities. Here we have interface ISorter, which defines common behaviour of our implementing classes, BubbleSorter and MergeSorterClient uses our factory Creator, which instantiates appropriate class.


Now in JavaScript:
function BubbleSorter() {
   this.sort = function (arr) {
        return "product A";
    }
}

function MergeSorter() {
   this.sort = function (arr) {
        return "product B";
    }
}

function Creator() {
    this.create = function(num) {
        if (num % 2 === 0) {
            return new BubbleSorter();
        }
        return new MergeSorter();
    }
}

var i, product, c = new Creator();
for (i = 0; i < 2; i += 1) {
    sorter = c.create(i);
    console.log(sorter.sort([5,2,7,3]));
}
Which produces the results:
bubble sorted
merge sorted

Conslusion


In Abstract Factory pattern, client is unaware of the specific factory used to instantiate the needed class, where as in Factory Method, a known factory is used.

Next time we'll continue our discussion about JavaScript design patterns and will cover additional creational patterns.

Sunday, June 22, 2014

Publish-Subscribe Pattern with Postal.js


Last week we talked about testing JavaScript Testing with Jasmine and today I'd like to continue our conversation about testing rather from different angle - separation of concerns. Once the code slips developers' fingers, it is hard to find time and strength to rewrite, it making it more testable. What works, may never be rewritten, sounds a bit like Iron island refrain What is dead, may never die :) Hmm - sorry for that! Nearly all today's applications have some calls to somewhere to retrieve the data. Front side retrieves from the server. Server side retrieves from services or database. Some manipulate it, others just format it and present as it is. Take a look at the following examples:
function someLogic() {
 $.get("ajax/test.html", function (data) {
  $(".result").html(data);
 }); 
}
function someLogic() {
 dataManager.getClients(function (err, data) {
  if (!err) {
   doSomething(data);
  }  
 }); 
}
How can you test it? First of all the server is needed to send the data. Secondly the data should always be the same to write our test specs correctly. Surely both are achievable, however wouldn't it be great if you could write the code in a way it's both clear and testable. This is where publish–subscribe pattern shines or pub/sub. Following the pattern ensures that your data receivers, or  subscribers, are totally separated from data producers, or publishers. The concept is represented in the following illustration:


A publisher observes the bus and when an event of interest is observed, a notification is created and sent to the notification engine. The notification is then matched against the subscribers that have expressed interest in the notification and prepared for the delivery. This model separates the management of the subscriptions, the matching process and the final delivery to the subscribers. There are currently two JavaScript libraries, which implement this pattern: Postal.js and Amplify.js. Since Amplify.js doesn't support server side programming and in the front side domain, Postal.js offers much more extensibility, we'll be focusing our conversation of Postal.js only.

Postal.js


Postal.js is an in-memory message bus - very loosely inspired by AMQP - written in JavaScript. Postal.js runs in the browser, or on the server using node.js. It takes the familiar "eventing-style" paradigm (of which most JavaScript developers are familiar) and extends it by providing "broker" and subscriber implementations, which are more sophisticated than what you typically find in simple event delegation.

In order to start working with the library, you should also add a reference to ConduitJS, since it's dependent on it. At first we need to create a channel, through which your messages will flow. The beauty of Postal.js is your ability to create named channels and separate completely your service buses by domains. If you don't need this ability, just create a default one without passing any name. Having our channel in place, we can subscribe to the events of interest and publish data to it. We called our event name.change, however you can call yours as you like. The dot separation though will come useful in the future.
var channel = postal.channel();
// subscribe to 'name.change' topics
var subscriber = channel.subscribe("name.change", function (data) {
 $("#example1").html("Name: " + data.name);
});
// And someone publishes a name change:
channel.publish("name.change", { name : "Dr. Who" });
// To unsubscribe, you:
subscriber.unsubscribe();
The data will flow through Postal's engine and be delivered to all the subscribers. The example present was rather dull, don't you agree? Let's spice it up by subscribing to change event of any object. We'll use the dot convention presented earlier and subscribe to event following the pattern *.change.
var subscriber = channel.subscribe("*.changed", function (data) {
 var i = $("
  • " + data.type + " -> " + data.value + "
  • "); i.appendTo("#example2"); } ); channel.publish("name.changed", {type: "Name", value: "John"}); channel.publish("country.changed",{type: "Country", value: "USA"}); subscriber.unsubscribe();
    As you can see both name.changed and country.changed are caught now. The pattern can be changed to name.*, which will catch all events related to name object like name.init or name.change. Postal.js supports additional patterns, have a look at their documentation to learn more.

    As said before, there are a lot of plugins written for Postal.js, making this library insanely useful. The most prominent are postal.when, providing even more targeted functionality to subscribers, and postal.federation delivering a framework to federate (or bridge) multiple instances of postal together, across various boundaries (frame/window, websocket, redis pub/sub, 0mq, etc.).

    We'll be talking more about messaging patterns in the future and various design patterns as well.
    Sunday, June 15, 2014

    JavaScript Testing with Jasmine


    For years, JavaScript developers checked their code by amm uhmm - exactly, they didn't. The QA, if there was one, tested the overall UI end to end. However no one really checked the code as it was accustomed with server side languages.

    Later testing frameworks started to emerge. QUnit pioneered the domain, which was followed by Jasmine and in the end Mocha appeared. All these framework matured with time and became standard in the industry. Nowadays, there is absolutely no excuse for JavaScript developer to write a code without writing the tests.

    Which one?


    As I've mentioned, currently there are three frameworks, which are mature enough to be considered by us. I personally prefer Jasmine over others, since it's already packaged with test double function (spy) and assertion framework and offers fairly headless running. For those who prefer configuring different aspects and implementations of your testing framework should look at Mocha. Moreover have a look at a comparison article with pros and cons of all networks, and decide what suits you best. The syntax in all of them is nearly the same, so you can easily migrate from one to another.

    Jasmine


    Jasmine is a behavior-driven development framework for testing JavaScript code. Your tests are separated into suits, which contains several tests, called specs. Think of suit as of test case. To overview the framework, we will be using the examples provided with the Jasmine distribution, using the latest at the time of writing - 2.0.0. Look at the structure of our folders. Our classes reside under folder named src. There we have two files Player and Song, which has only one method throwing an exception.
    function Player() {
    }
    Player.prototype.play = function(song) {
     this.currentlyPlayingSong = song;
     this.isPlaying = true;
    };
    
    Player.prototype.pause = function() {
     this.isPlaying = false;
    };
    
    Player.prototype.resume = function() {
     if (this.isPlaying) {
      throw new Error("song is already playing");
     }
    
     this.isPlaying = true;
    };
    
    Player.prototype.makeFavorite = function() {
     this.currentlyPlayingSong.persistFavoriteStatus(true);
    };
    
    
    function Song() {
    }
    
    Song.prototype.persistFavoriteStatus = function(value) {
      // something complicated
      throw new Error("not yet implemented");
    };
    
    We'll start by looking at a first suit:
    describe("Player", function() {
      var player;
      var song;
    
      beforeEach(function() {
        player = new Player();
        song = new Song();
      });
    
      it("should be able to play a Song", function() {
        player.play(song);
        expect(player.currentlyPlayingSong).toEqual(song);
    
        //demonstrates use of custom matcher
        expect(player).toBePlaying(song);
      });
    
    We see here a test suit, called Player, in which we declare one spec using it function. Notice the beforeEach function - everything inside it is run before each spec is executed. The real magic happens when expect function is executed. Firstly we call play method of Player class, which is supposed to assign the property currentlyPlayingSong with the passed parameter. After that we check if it indeed does what is supposed by executing expect(player.currentlyPlayingSong).toEqual(song). It performs exactly what it is written - expects the passed parameter to be equal to the song variable. If the variables are not the same, exception is thrown.

    The next spec uses custom matcher declared in spec/SpecHelper.js, which performs the comparison based on several criterias.
    beforeEach(function () {
      jasmine.addMatchers({
        toBePlaying: function () {
          return {
            compare: function (actual, expected) {
              var player = actual;
    
              return {
                pass: player.currentlyPlayingSong === 
                  expected && player.isPlaying
              }
            }
          };
        }
      });
    });
    
    Jasmine comes with lots of build-in matchers, so before you create your own, make sure it isn't already defined. Moving on to the second suit and being amazed by more matchers :)
    describe("when song has been paused", function() {
      beforeEach(function() {
        player.play(song);
        player.pause();
      });
    
      it("should indicate that song is currently paused", function() {
        expect(player.isPlaying).toBeFalsy();
    
        // demonstrates use of 'not' with a custom matcher
        expect(player).not.toBePlaying(song);
      });
    
      it("should be possible to resume", function() {
        player.resume();
        expect(player.isPlaying).toBeTruthy();
        expect(player.currentlyPlayingSong).toEqual(song);
      });
    });  
    
    Since this suit is nested within the first one, the beforeEach is "added" to the one declared earlier. Thus player and song variables will be already defined. ToBeTruthy and ToBeFalsy are a bit tricky at first, both refer to anything that is considered true and false in JavaScript like null, 0 and undefined. Play around with them in specially created Jasmine cheat sheet.
    it("checks if current song has been made favorite", function() {
      spyOn(song, 'persistFavoriteStatus');
    
      player.play(song);
      player.makeFavorite();
    
      expect(song.persistFavoriteStatus).toHaveBeenCalledWith(true);
    });
    In the beginning we tell Jasmine on which method we want to spy using spyOn function - persistFavoriteStatus method of instance song. Later we call some methods, which suppose to call the spied method and in the end we test if it was called and with which parameters.

    We finish our presentation with the last suit, which demonstrates the ability to check for thrown exceptions using toThrowError function.
    describe("#resume", function() {
      it("should throw an exception if song is already playing", 
        function() {
          player.play(song);
    
          expect(function() {
            player.resume();
          }).toThrowError("song is already playing");
        });
    });
    
    This is not exception handling feature and shouldn't be used in your live code. Use try-catch instead.

    Don't worry if still feel you haven't grasped the topic yet, I'll be writing more about JavaScript testing and Jasmine in particular. Today was just an introduction and overview of the concept and main features.
    Sunday, June 8, 2014

    Bower and Require.js Integration


    In the past we've talked about Bower package manager and God knows, I have been obsessively repeating myself about using Require.js and it's integration with object oriented programming. So how do they integrate with each other? In this article we'll cover the integration of both and see how they get along together.

    Bower Initiation


    Let's start by defining, which packages we want to use in our project by filling the bower.json. You can create one yourself or run bower init command for interactive creation.
    {
        "name": "RequireJS Starter",
        "version": "1.0.0",
        "dependencies": {
            "jquery": "1.9",
            "underscore": null,
            "requirejs": null
        }
    }
    
    So we'll be needing jQuery, Underscore and of course Require.js. Putting null as a version number will download the latest version. Now run bower install to download all the packages into bower_components folder. You can change the location along with other thing using .bowerrc configuration file. After everything is in place, we'll configure our dependencies in our entry point JavaScript file and use the libraries once retrieved:
    require.config({
        paths: {
            "jquery": "bower_components/jquery/jquery",
            "underscore": "bower_components/underscore/underscore"
        }
    });
    require(['jquery', 'underscore'], function($, _) {
        $('body').text(_.range(10));
    });

    Automagical wire-up


    This is how it works according to the writter of bower-requirejs plugin. It looks at the libraries installed by Bower and creates a JavaScript file with require.config call with all the paths in place. Just run the following line in your bash console:
    ./node_modules/.bin/bower-requirejs -c destination/config.js
    
    It has some interesting flags you can use, all of them well described in the documentation.

    CDN Integration


    But my mother told me local libraries are bad. She was right! We should always try to use CDN for common libraries, since chances are it had been already downloaded to user's computer and cached version would be used instead of downloading fresh version from our server. Let's edit our code and add cdnjs urls as a first priority. I prefer them over others because they offer the biggest variety of libraries and it's always good practice to work with a single provider. We'll leave our versions as a fallback if something bad happens to the CDN:
    require.config({
        paths: {
            "jquery": ["http://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.1/jquery.min", "bower_components/jquery/jquery"],
            "underscore": ["http://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.6.0/underscore-min", "bower_components/underscore/underscore"]
        },
        waitSeconds: 10
    });
    require(['jquery', 'underscore'], function($, _) {
        $('body').text(_.range(10));
    });
    
    Notice the waitSeconds parameter we've added configuring how much time to wait for the CDN's versions. Hope things started to clear bit by bit. What to use and how to use it. I'll continue to write articles on this topic including Grunt integration.
    Sunday, June 1, 2014

    CSS and JavaScript Live Editing


    As planned we're continuing our tradition to present JavaScript Developer Toolkit. Last time we've talked about Emmet and today's article I'd like to devote to HTML/CSS/JavaScript editing.

    How often do you change your CSS rules and JavaScript within your browser? How often do copy/paste the changes made into appropriate resource files? It's time to do this Zen style.

    IDE integration


    This is my preferable way to develop and live-editing the changes. Let me show you why. Wouldn't it be cool if you could develop using your beloved IDE with all the neat plugins it offers and see the changes reflected live in the browser? Well - you can, with both Sublime Text and Webstorm we've talked about during our previous JavaScript toolkit article. You do this by installing JetBrains IDE Chrome extension for Webstorm:


    or Emmet LiveStyle for Sumblime Text:


    Look into their sites and see how properly things should to be configured. Both tools only offer support for Chrome, so Firefox fans will have to wait for now...

    Browser Extensions


    As time passed, passionate developers have been creating bunch of extensions both for Chrome and Firefox to enable this functionality. The most prominent ones are Chrome DevTools Autosave and EditCSS. However this work has not only inspired the developer community, but also the creators of both most commonly used browsers. As a result as of Firefox 11 and Chrome 28 the functionality has been bundled with the browsers, making the extensions obsolete.

    Browser built-in capabilities


    While Firefox has done some progress and enabled the live editing of CSS using it's Style Editor, the real advancement came from Google camp with the introduction of workspaces. It allows one to save both CSS rules and JavaScript code and even supports Sass debugging of Sass (.scss) files in the Sources panel, and view the results without having to leave DevTools or refresh the page. When you inspect an element whose styles are provided by a Sass-generated CSS file, the Elements panel displays a link to the .scss file, not the generated .css file. We'll talk more about Sass and Compass in the future. Find the time to watch the whole presentation about this feature: