SOLID JavaScript: The Liskov Substitution Principle

On December 31, 2011, in Uncategorized, by derekgreer

This is the thrid installment in the SOLID JavaScript series which explores the SOLID design principles within the context of the JavaScript language. In this installment, we’ll be covering the Liskov Substitution Principle.

 

The Liskov Substitution Principle

The Liskov Substitution Principle relates to the interoperability of objects within an inheritance hierarchy.  The principle states:

Subtypes must be substitutable for their base types.

In object-oriented programming, inheritance provides a mechanism for sharing code within a hierarchy of related types.  This is achieved through a process of encapsulating any common data and behavior within a base type, and then defining specialized types in terms of the the base type.  To adhere to the Liskov Substitution Principle, a derived type should be semantically equivalent to the anticipated behavior of its base type.

To help illustrate, consider the following code:

function Vehicle(my) {
    my = my || {};
    my.speed = 0;
    my.running = false;

    this.speed = function() {
        return my.speed;
    };
    this.start = function() {
        my.running = true;
    };
    this.stop = function() {
        my.running = false;
    };
    this.accelerate = function() {
        my.speed++;
    };
    this.decelerate = function() {
        my.speed--;
    };
    this.state = function() {
        if (!my.running) {
            return "parked";
        }
        else if (my.running && my.speed) {
            return "moving";
        }
        else if (my.running) {
            return "idle";
        }
    };
}

This listing shows a Vehicle constructor which provides a few basic operations for a vehicle object.  Let’s say this constructor is currently being used in production by several clients.  Now, consider we’re asked to add a new constructor which represents faster moving vehicles.  After thinking about it for a bit, we come up with the following new constructor:

function FastVehicle(my) {
    my = my || {};
    
    var that = new Vehicle(my);
    that.accelerate = function() {
        my.speed += 3;
    };
    return that;
}

After testing out our new FastVehicle constructor in the browser’s console window, we’re satisfied that everything works as expected.  Objects created with FastVehicle accelerate 3 times faster than before and all the inherited methods function as expected.  Confident that everything works as expected, we decide to deploy the new version of the library.  Upon using the new type, however, we’re informed that objects created with the FastVehicle constructor break existing client code.  Here’s the snippet of code that reveals the problem:

var maneuver = function(vehicle) {
    write(vehicle.state());
    vehicle.start();
    write(vehicle.state());
    vehicle.accelerate();
    write(vehicle.state());
    write(vehicle.speed());
    vehicle.decelerate();
    write(vehicle.speed());
    if (vehicle.state() != "idle") {
        throw "The vehicle is still moving!";
    }
    vehicle.stop();
    write(vehicle.state());
};

Upon running the code, we see that an exception is thrown: “The vehicle is still moving!”.  It appears that the author of this function made the assumption that vehicles always accelerate and decelerate uniformly.  Objects created from our FastVehicle aren’t completely substitutable for objects created from our base Vehicle constructor.  Our FastVehicle violates the Liskov Substitution Principle!

At this point, you might be thinking: “But, the client shouldn’t have assumed all vehicles will behave that way.” Irrelevant!  Violations of the Liskov Substitution Principle aren’t based upon whether we think derived objects should be able to make certain modifications in behavior, but whether such modifications can be made in light of existing expectations.

In the case of this example, resolving the incompatibility issue will require a bit of redesign on the part of the vehicle library, the consuming clients, or perhaps both.

Mitigating LSP Violations

So, how can we avoid Liskov Substitution Principle Violations?  Unfortunately, this isn’t always possible.  To avoid LSP violations altogether, you would be faced with the difficult task of anticipating every single way a library might ever be used.  Add to this the possibility that you might not be the original author of the code you’re being asked to extend and you may not have visibility into all the ways the library is currently being used.  That said, there are a few strategies for heading off violations within your own code.

Contracts

One strategy for heading off the most egregious violations of the LSP is to use contracts.  Contracts manifest in two main forms: executable specifications and error checking.  With executable specifications, the contract for how a particular library is intended to be used is contained in a suite of automated tests.  The second approach is to include error checking directly in the code itself in the form of preconditions, postconditions and invariant checks.  This technique is known as Design By Contract, a term coined by Bertrand Meyer, creator of the Eiffel programming language.  The topics of automated testing and Design By Contract are beyond the scope of this series, but I’ll leave you with the following recommendations for when to use each.

  • Always use Test-Driven Development to guide the design of your own code
  • Optionally use Design By Contract techniques when designing reusable libraries

For code you’ll be maintaining and consuming yourself, the use of Design By Contract techniques tends to just add a lot of unnecessary noise and overhead to your code.  If you’re in control of the input, a test suite serves as a better control for specifying how a library is intended to be used.  If you’re authoring reusable libraries, Design By Contract techniques serve both to guard against improper usage and as a debugging tool for your users.

Avoid Inheritance

Another strategy for avoiding LSP violations is to minimize the use of inheritance where possible.  In the book Design Patterns – Elements of Reusable Object-Orineted Software by. Gamma, et. al., we find the following advice:

Favor object composition over class inheritance

While some of the book’s discussion concerning the advantages of composition over inheritance is only relevant to statically typed, class-based languages (e.g. the inability to change behavior at run time), one of the issues relevant to JavaScript is that of coupling.  When using inheritance, the derived types are coupled with their based types.  This means that changes to the base type may inadvertently affect derived types.  Additionally, composition tends to lead to smaller, more focused objects which are easier to maintain for static and dynamic languages alike.

It About Behavior, Not Inheritance

Thus far, we’ve discussed the Liskov Substitution Principle within the context of inheritance, which is perfectly appropriate given that JavaScript is an object-oriented language.  However, the essence of the Liskov Substitution Principle isn’t really concerned with inheritance, but behavioral compatibility.  JavaScript is a dynamic language, therefore the contract for an object’s behavior isn’t determined by the type of the object, but by the capabilities expected by the object.  While the Liskov Substitution Principle was originally conceived as a guiding principle for inheritance, it is equally relevant to the design of objects adhering to implicit interfaces.

To illustrate, let’s consider an example taken from the book Agile Software Development, Principles, Patterns, & Practices by Robert C. Martin: the rectangle example.

The Rectangle Example

Consider that we have an application which uses a rectangle object defined as follows:

var rectangle = {
    length: 0,
    width: 0
};

Later, it’s determined that the application also needs to work with a square.  Based on the knowledge that a square is a rectangle whose sides are equal in length, we decide to create a square object to use in place of rectangle.  We add length and width properties to match the rectangle object’s definition, but we decide to use property getters and setters so we can keep the length and width values in sync, ensuring it adheres to the definition of a square:

var square = {};
(function() {
    var length = 0, width = 0;
    Object.defineProperty(square, "length", {
        get: function() { return length; },
        set: function(value) { length = width = value; }
    });
    Object.defineProperty(square, "width", {
        get: function() { return width; },
        set: function(value) { length = width = value; }
    });
})();

Unfortunately, a problem is discovered when the application attempts to use our square in place of rectangle.  It turns out that one of the methods computes the rectangle’s area like so:

var g = function(rectangle) {
    rectangle.length = 3;
    rectangle.width = 4;
    write(rectangle.length);
    write(rectangle.width);
    write(rectangle.length * rectangle.width);
};

When the method is invoked with square, the product is 16 rather than the expected value of 12.  Our square object violates the Liskov Substitution Principle with respect to the function g.  In this case, the presence of the length and width properties was a hint that our square might not end up being 100% compatible with rectangle, but we won’t always have such obvious hints.  Correcting this situation would likely require a redesign of the shape objects and the consuming application.  A more flexible approach might be to define rectangles and squares in terms of polygons.  Regardless, the important take away from this example is that the Liskov Substitution Principle isn’t just relevant to inheritance, but to any approach where one behavior is being substituted for another.

Next time, we’ll discuss the forth principle in the SOLID acronym: The Interface Segregation Principle.

Tagged with:  

SOLID JavaScript: The Open/Closed Principle

On December 19, 2011, in Uncategorized, by derekgreer

This is the second installment in the SOLID JavaScript series which explores the SOLID design principles within the context of the JavaScript language. In this installment, we’ll be covering the Open/Closed Principle.

 

The Open/Closed Principle

The Open/Closed Principle relates to the extensibility of objects. The principle states:

Software entities (classes, modules, functions, etc.) should be open for extension but closed for modification.

By open for extension, this principle means the ability for an entity to be adapted to meet the changing needs of an application. By closed for modification, this principle means that the adaptation of an entity should not result in modification of the entity’s source. More simply, entities which perform varied behavior should be designed to facilitate variability without the need for modification. Adherence to the Open/Closed Principle can help to improve maintainability by minimizing changes made to working code.

To help illustrate, let’s take a look at the following example which dynamically renders questions to a screen based upon the type of answer expected for each question:

 

 
var AnswerType = {
    Choice: 0,
    Input: 1
};

function question(label, answerType, choices) {
    return {
        label: label,
        answerType: answerType,
        choices: choices
    };
}

var view = (function() {
    function renderQuestion(target, question) {
        var questionWrapper = document.createElement('div');
        questionWrapper.className = 'question';

        var questionLabel = document.createElement('div');
        questionLabel.className = 'question-label';
        var label = document.createTextNode(question.label);
        questionLabel.appendChild(label);

        var answer = document.createElement('div');
        answer.className = 'question-input';

        if (question.answerType === AnswerType.Choice) {
            var input = document.createElement('select');
            var len = question.choices.length;
            for (var i = 0; i < len; i++) {
                var option = document.createElement('option');
                option.text = question.choices[i];
                option.value = question.choices[i];
                input.appendChild(option);
            }
        }
        else if (question.answerType === AnswerType.Input) {
            var input = document.createElement('input');
            input.type = 'text';
        }

        answer.appendChild(input);
        questionWrapper.appendChild(questionLabel);
        questionWrapper.appendChild(answer);
        target.appendChild(questionWrapper);
    }

    return {
        render: function(target, questions) {
            for (var i = 0; i < questions.length; i++) {
                renderQuestion(target, questions[i]);
            };
        }
    };
})();

var questions = [
    question('Have you used tobacco products within the last 30 days?', AnswerType.Choice, ['Yes', 'No']),
    question('What medications are you currently using?',AnswerType.Input)
    ];

var questionRegion = document.getElementById('questions');
view.render(questionRegion, questions);

In this example, a view object contains a render method which renders questions based upon each type of question received. A question consists of a label, an answer type (choice or text entry), and an optional list of choices. If the answer type is Answer.Choice, a drop down is created with the options provided. If the answer type is AnswerType.Input, a simple text input is rendered.

Following the pattern already established, adding new input types would require adding new conditions within the render method. This would violate the Open/Closed Principle.

Let’s take a look at an alternate implementation that would allow us to extend the view object’s rendering capabilities without requiring changes to the view object for each new answer type :

 

function questionCreator(spec, my) {
    var that = {};

    my = my || {};
    my.label = spec.label;

    my.renderInput = function() {
        throw "not implemented";
    };

    that.render = function(target) {
        var questionWrapper = document.createElement('div');
        questionWrapper.className = 'question';

        var questionLabel = document.createElement('div');
        questionLabel.className = 'question-label';
        var label = document.createTextNode(spec.label);
        questionLabel.appendChild(label);

        var answer = my.renderInput();

        questionWrapper.appendChild(questionLabel);
        questionWrapper.appendChild(answer);
        return questionWrapper;
    };

    return that;
}

function choiceQuestionCreator(spec) {

    var my = {},
        that = questionCreator(spec, my);

    my.renderInput = function() {
        var input = document.createElement('select');
        var len = spec.choices.length;
        for (var i = 0; i < len; i++) {
            var option = document.createElement('option');
            option.text = spec.choices[i];
            option.value = spec.choices[i];
            input.appendChild(option);
        }

        return input;
    };

    return that;
}

function inputQuestionCreator(spec) {

    var my = {},
        that = questionCreator(spec, my);

    my.renderInput = function() {
        var input = document.createElement('input');
        input.type = 'text';
        return input;
    };

    return that;
}

var view = {
    render: function(target, questions) {
        for (var i = 0; i < questions.length; i++) {
            target.appendChild(questions[i].render());
        }
    }
};

var questions = [
    choiceQuestionCreator({
    label: 'Have you used tobacco products within the last 30 days?',
    choices: ['Yes', 'No']
}),
    inputQuestionCreator({
    label: 'What medications are you currently using?'
})
    ];

var questionRegion = document.getElementById('questions');

view.render(questionRegion, questions);

There’s a few techniques being used here, so let’s walk through them one at a time.

First, we’ve factored out the code responsible for creating questions into a functional constructor named questionCreator. This constructor utilizes the Template Method Pattern for delegating the creation of each answer to extending types.

Second, we’ve replaced the use of the former constructor’s properties  with a private spec property  which serves as the questionCreator constructor’s interface. Since we’re encapsulating the rendering behavior with the data it operates upon, we no longer need these properties to be publicly accessible.

Third, we’ve identified the code which creates each answer type as a family of algorithms and factored out each algorithm into a separate object (a technique referred to as the the Strategy Pattern) which extends the questionCreator object using differential inheritance.

As an added benefit to this refactoring, we were able to eliminate the need for an AnswerType enumeration and we were able make the choices array a requirement specific to the choiceQuestionCreator interface.

The refactored version of the view object can now be cleanly extended by simply extending new questionCreator objects.

Next time, we’ll discuss the third principle in the SOLID acronym: The Liskov Substitution Principle.

Tagged with:  

Acronyms and Ubiquitous Language

On December 11, 2011, in Uncategorized, by derekgreer

Acronyms are often employed within organizations as a way to abbreviate frequently used phrases in an attempt to expedite communication.  Unfortunately, their use often does the exact opposite.  Many programming language style guides discourage the use of acronyms.  For instance, here’s what the .Net Framework General Naming Conventions has to say on the use of acronyms:

Do not use any acronyms that are not widely accepted, and then only when necessary.

The reasoning for this is that acronyms tend to present a barrier to understanding rather than their intended goal of expediting communication.  When used in conversation, if you’re confronted with an unfamiliar acronym then you at least have an opportunity to ask “What does XYZ stand for?”, but when a developer is reading through a new code base and encounters unfamiliar acronyms then there isn’t always an expedient way of bridging that communication barrier.

Some might ask: “But what do we do when acronyms are a deeply rooted part of the business’s day-to-day language?

The use of a common language between developers and the business is referred to in Domain Driven Design as “Ubiquitous Language”.  The book Domain-Driven Design by Eric Evans has this to say concerning the use of a shared language with the business:

A project faces serious problems when its language is fractured.  Domain experts use their jargon while technical team members have their own language tuned for discussing the domain in terms of design.

The terminology of day-to-day discussions is disconnected from the terminology embedded in the code (ultimately the most important product of a software project).  And even the same person uses different language in speech and in writing, so that the most incisive expression of the domain often emerge in a transient form that is never captured in the code or even in writing.

Translation blunts communication and makes knowledge crunching anemic.  Yet none of these dialects can be a common language because none serves all needs.

Therefore:

Use the model as the backbone of a language.  Commit the team to exercising that language relentlessly in all communication within the team and in the code.  Use the same language in diagrams, written, and especially speech.

Iron out difficulties by experimenting with alternative expressions, which reflect alternative models.  The refactor the code, renaming classes, methods, and modules to conform to the new model.  Resolve confusion over terms in conversation, in just the way we come to agree on the meaning of ordinary words.

Recognize that a change in the UBIQUITOUS LANGUAGE is a change to the model.

Domain experts should object to terms or structures that are awkward or inadequate to convey domain understanding; developers should watch for ambiguity or inconsistency that will trip up design.

 

At first, some may see this as a call to adopt the business’s acronyms as part of the Ubiquitous Language, and in some cases this might be the right thing to do (I’ll touch on this more in a bit), but let’s first consider a few things about what’s intended by using a Ubiquitous Language.

First, the avocation of a Ubiquitous Language is first and foremost to facilitate communication and understanding.  The job of the developer is to model the domain of the business in code, so adopting a common language with the business helps facilitate the creation of, and conversations about the model in ways that promote communication and understanding.  That said, if the Ubiquitous Language isn’t promoting communication and understanding then you’re doing it wrong.

 

cargo_cult_3  Other people doing it wrong  

Second, the fractured language Evans is referring to is the use of technical jargon to describe business concepts, not whether the concepts are expressed in abbreviated form or not.  Expansion of business acronyms within the code doesn’t necessarily constitute a departure from the Ubiquitous Language.

Third, the formation of the Ubiquitous Language is a two-way street.  Business experts don’t always share a consistent language amongst themselves, and sometimes the terms they’ve grown accustomed to are ambiguous, confusing, or simply wrong.  In these cases, the role of the development team should be to help forge a Ubiquitous Language with the user by agreeing upon terminology which clearly conveys understanding of the domain for both parties.

That said, there are times when the use of business-specific acronyms may be appropriate.  In cases where the use of acronyms are minimal and perhaps central to the identity of the business, using the acronyms in code may even be desirable.  For example, imagine your company has won a bid to write an application for the Ultimate Fighting Championship company to keep track of tournament brackets for Pay Per View events.  For such an application, it would be completely appropriate to use the commonly used abbreviation for the company: UFC.  

If there are only a few acronyms used in the business which wouldn’t be prohibitive to learn then their use probably won’t pose much of an issue, but if the language of the business is flooded with acronyms then it’s best to use their expanded forms.

I once worked at a company whose primary contract was with the United States Military.  If you’ve never been exposed to military jargon before, I can tell you they take the use of acronyms to the extreme.  The use of acronyms were littered throughout the code which made understanding the domain difficult for all.  I recall several of the senior members of the team which had been with the company for years admitting that they only understood a small percentage of what the acronyms meant, and one junior developer explained that they didn’t know what a certain acronym used for a property meant, but they knew that that it always had to start with a certain sequence of letters.  As it turned out, there was actually some correlation between the sequence of letters and the meaning of the acronym which was lost on all.  Recommendations to stop using acronyms were met with objections that the team should continue using them because it was the “Ubiquitous Language”.  Ironically, due to the way the U.S. Military conducted business with the company, only the management staff ever met with the generals for which a real Ubiquitous Language would have become useful, and then only rarely.  Unfortunately, these choices among others lead to low quality and a high turn over rate among the development staff.

In summary, acronyms may sound like a good idea because they save a few key strokes or syllables here and there, but before you use them in your code ask yourself if the code will be more or less understandable to the other developers who come after you.  Additionally, if you’re using them under the banner of adhering to a “Ubiquitous Language” then ask yourself whether their use is really achieving a goal of promoting communication and understanding.

Tagged with:  

This is the first installment in the SOLID JavaScript series which will explore the SOLID design principles within the context of the JavaScript language.  In this first installment, we’ll take a look at what principles comprise the SOLID design principles and discuss the first of these principles: The Single Responsibility Principle.

 

The SOLID Design Principles and JavaScript

SOLID is a mnemonic acronym referring to a collection of design principles which evolved out of the objected-oriented community and were popularized by the writings of Robert C. Martin.    These principles are as follows:

  • The Single Responsibility Principle
  • The Open/Closed Principle
  • The Liskov Substitution Principle
  • The Interface Segregation Principle
  • The Dependency Inversion Principle

These principles are often discussed within the context of classical, statically typed, objected-oriented languages, and while JavaScript is a prototype-based, dynamically typed language blending concepts from both object-oriented and functional paradigms, programmers can still reap the benefits from the application of these principles to JavaScript.  This article will cover the first of these principles: The Single Responsibility Principle.

The Single Responsibility Principle

The Single Responsibility Principle relates to the functional relatedness of the elements of a module.  The principle states:

A class should have only one reason to change

This description can be a little misleading as it would seem to suggest that an object should only do one thing. What is meant by this assertion, however, is that an object should have a cohesive set of behaviors, together comprising a single responsibility that, if changed, would require the modification of the object’s definition.  More simply, an object’s definition should only have to be modified due to changes to a single responsibility within the system.

Adherence to the Single Responsibility Principle helps to improve maintainability by limiting the responsibilities of an object to those which change for related reasons.  When an object encapsulates multiple responsibilities, changes to the object for one of the responsibilities can negatively impact the others.  By decoupling such responsibilities, we can create code that is more resilient to change.

But how do we identify whether a given set of behaviors constitutes a single responsibility?  Would grouping all string manipulation into a single object be a single responsibility?  How about grouping together all the service calls made within an application?  Without an established approach to making these determinations, adhering to the Single Responsibility can be a bit perplexing.

Object Role Stereotypes

One approach which can aid in the organization of behavior within a system is the use of Object Role Stereotypes.  Object Role Stereotypes are a set of general, pre-established roles which commonly occur across object-oriented architectures.  By establishing a set of role stereotypes, developers can provide themselves with a set of templates which they can use as they go through the mental exercise of decomposing behavior into cohesive components.

The concept of Object Role Stereotypes is discussed in the book Object Design: Roles, Responsibilies, and Collaborations by Rebecca Wirfs-Brock and Alan McKean.  The book presents the following stereotypes::

  • Information holder – an object designed to know certain information and provide that information to other objects.
  • Structurer – an object that maintains relationships between objects and information about those relationships.
  • Service provider – an object that performs specific work and offers services to others on demand.
  • Controller – an object designed to make decisions and control a complex task.
  • Coordinator – an object that doesn’t make many decisions but, in a rote or mechanical way, delegates work to other objects.
  • Interfacer – an object that transforms information or requests between distinct parts of a system.

While not prescriptive, this set of role stereotypes provides an excellent mental framework for aiding in the software design process.  Once you have an established  set of role stereotypes to work within, you’ll find it easier to group behaviors into cohesive groups of responsibilities related to the object’s intended role.

Single Responsibility Principle Example

To illustrate the application of the Single Responsibility Principle, let’s consider the following example facilitates the movement of product items into a shopping cart:

function Product(id, description) {
    this.getId = function() {
        return id;
    };
    this.getDescription = function() {
        return description;
    };
}

function Cart(eventAggregator) {
    var items = [];

    this.addItem = function(item) {
        items.push(item);
    };
}

var products = [
    new Product(1, "Star Wars Lego Ship"),
    new Product(2, "Barbie Doll"),
    new Product(3, "Remote Control Airplane")],
    cart = new Cart();

(function() {
    function addToCart() {
        var productId = $(this).attr('id');
        var product = $.grep(products, function(x) {
            return x.getId() == productId;
        })[0];
        cart.addItem(product);

        var newItem = $('<li></li>')
            .html(product.getDescription())
            .attr('id-cart', product.getId())
            .appendTo("#cart");
    }

    products.forEach(function(product) {
        var newItem = $('<li></li>')
            .html(product.getDescription())
            .attr('id', product.getId())
            .dblclick(addToCart)
            .appendTo("#products");
    });
})();
/pre>

While not overly complex, this example illustrates a number of unrelated responsibilities which are grouped together within a single anonymous function. Let’s consider each responsibility:

First, we have behavior defined to handle populating the Cart model when an item is double-clicked.

Second, we have behavior defined to add items to the cart view when an item is double-clicked.

Third, we have behavior defined to populate the products view with the initial set of products.

Let’s break these three responsibilities out into their own objects:

 

function Event(name) {
    this._handlers = [];
    this.name = name;
}
Event.prototype.addHandler = function(handler) {
    this._handlers.push(handler);
};
Event.prototype.removeHandler = function(handler) {
    for (var i = 0; i < handlers.length; i++) {
        if (this._handlers[i] == handler) {
            this._handlers.splice(i, 1);
            break;
        }
    }
};
Event.prototype.fire = function(eventArgs) {
    this._handlers.forEach(function(h) {
        h(eventArgs);
    });
};

var eventAggregator = (function() {
    var events = [];

    function getEvent(eventName) {
        return $.grep(events, function(event) {
            return event.name === eventName;
        })[0];
    }

    return {
        publish: function(eventName, eventArgs) {
            var event = getEvent(eventName);

            if (!event) {
                event = new Event(eventName);
                events.push(event);
            }
            event.fire(eventArgs);
        },

        subscribe: function(eventName, handler) {
            var event = getEvent(eventName);

            if (!event) {
                event = new Event(eventName);
                events.push(event);
            }

            event.addHandler(handler);
        }
    };
})();

function Cart() {
    var items = [];

    this.addItem = function(item) {
        items.push(item);
        eventAggregator.publish("itemAdded", item);
    };
}

var cartView = (function() {
    eventAggregator.subscribe("itemAdded", function(eventArgs) {
        var newItem = $('<li></li>')
            .html(eventArgs.getDescription())
            .attr('id-cart', eventArgs.getId())
            .appendTo("#cart");
    });
})();

var cartController = (function(cart) {
    eventAggregator.subscribe("productSelected", function(eventArgs) {
        cart.addItem(eventArgs.product);
    });
})(new Cart());

function Product(id, description) {
    this.getId = function() {
        return id;
    };
    this.getDescription = function() {
        return description;
    };
}

var products = [
    new Product(1, "Star Wars Lego Ship"),
    new Product(2, "Barbie Doll"),
    new Product(3, "Remote Control Airplane")];

var productView = (function() {
    function onProductSelected() {
        var productId = $(this).attr('id');
        var product = $.grep(products, function(x) {
            return x.getId() == productId;
        })[0];
        eventAggregator.publish("productSelected", {
            product: product
        });
    }

    products.forEach(function(product) {
        var newItem = $('<li></li>')
            .html(product.getDescription())
            .attr('id', product.getId())
            .dblclick(onProductSelected)
            .appendTo("#products");
    });
})();

In our revised design, we’ve removed our anonymous function and replace it with objects to coordinate each of the separate set of responsibilities.  A cartView was introduced to coordinate the population of the cart display, a cartController was introduced to coordinate the population of the cart model, and a productView was introduced to coordinate the population of the products display.  We also introduced an Event Aggregator to facilitate communication between the objects in a loosely-coupled way.  While this design results in a larger number of objects, each object now focuses on fulfilling a specific role within the overall orchestration with minimal coupling between the objects.

Next time, we’ll discuss the next principle in the SOLID acronym: The Open/Closed Principle.

Tagged with:  

Adding JSLint To Your Build

On December 2, 2011, in Uncategorized, by derekgreer

JSLint, the popular JavaScript static code analysis tool written by Douglas Crockford, can fairly easily be incorporated into your builds through the use of node and the jslint node module.  The following steps will show you how to add JSLint to an existing rake build:

Step 1: Install Node

If you don’t already have it, go download and install node from http://nodejs.org/.

Step 2: Add JSLint Method

The following jslint method uses the Node Package Manager (npm) to install the jslint module into the current folder if it does not already exist.  If node or npm are not found in the execution path then an error message is printed and the method simply returns.  The method uses a hash config parameter for its parameters.

def jslint(config)
    tool = 'jslint'
    flags = config['flags'] || ''

    node = which('node')
    if(node.nil?)
        puts "Could not find node in your path."
        return
    end

    npm = which('npm')
    if(npm.nil?)
        puts "Could not find npm in your path."
        return
    end

    if(!File.directory?("node_modules/#{tool}"))
        sh "\"#{npm}\" install #{tool}"
    end

    scripts = config['scripts'] || [""]
    sh "\"#{node}\" node_modules/#{tool}/bin/#{tool}.js #{flags} #{scripts}"
end

def which(cmd)
    exts = ENV['PATHEXT'] ? ENV['PATHEXT'].split(';') : ['']
    ENV['PATH'].split(File::PATH_SEPARATOR).each do |path|
    exts.each { |ext|
        sep = File::ALT_SEPARATOR || File::SEPARATOR
        exe = "#{path}#{sep}#{cmd}#{ext}"
        return exe if File.executable? exe
    }
    end
    return nil
end

Step 3: Add a Lint Task

After including the jslint method defined above, add a new rake task which calls the method with the desired config values:

    task :lint do
        config = { 'flags'   => '--white',
                   'scripts' => FileList.new("src/**/app/*.js") }
        jslint(config)
    end

That’s all you need.  Now you can run “rake lint” or tie this into to your existing process as you see fit.  Enjoy!

Tagged with: