JavaScript Closures Explained

On February 17, 2012, in Uncategorized, by derekgreer

If you write any code in JavaScript then you’ve probably used closures, but do you actually understand what they are and how they work?  Taking the time to understand closures and how they’re implemented can add a deeper dimension to your understanding of the JavaScript language.  In this article, I’ll discuss what closures are and how they’re specified for the JavaScript language.

What Are Closures?

A closure is a pairing of a function along with its referencing environment such that identifiers within the function may refer to variables declared within the referencing environment.

Let’s consider the following example:

var createGreeting = function(greeting) {
    return function(name) {
        document.write(greeting + ', ' + name + '.');
    };
};


helloGreeting = createGreeting("Hello");
howdyGreeting = createGreeting("Howdy");

helloGreeting("John");  // Hello, John.
helloGreeting("Sally"); // Hello, Sally.
howdyGreeting("John");  // Howdy, John.
howdyGreeting("Sally"); // Howdy, Sally.

In this code, a function named createGreeting is defined which returns an anonymous function.  When the anonymous function is executed, it prints a greeting which consists of the outer function’s greeting parameter along with the inner function’s name parameter.  While the greeting parameter is neither a formal parameter  nor a local variable of the inner function (which is to say it is a free variable), it is still resolved when the function executes.  Moreover, the createGreeting function object is no longer in scope and may have even been garbage collected at the point the function executes.  How then does this work?

The inner function is capable of resolving the greeting identifier due to a closure which has been formed for the inner function.  That is to say, the inner function has been paired with its referencing (as opposed to its calling) environment.

Conceptually, we can think of our closure as the marriage between a function and the environment in which it was declared within:

closure2

 

Exactly what this marriage looks like at an implementation level differs depending on the language.  In C# for instance, closures are implemented by the instantiation of a compiler-generated class which encapsulates a delegate and the variables referenced by the delegate from its declaring scope. In JavaScript, the function object itself contains a non-accessible property pointing to an object containing the variables from its declaring scope.  While each implementation differs, both render a function that has access to what its environment looked like at the point it was created.

Let’s move on to examining how JavaScript closures work from a specification perspective.

JavaScript Closures

To understand how closures work in JavaScript, it helps to have a grasp of the underlying concepts set forth within the ECMAScript Language Specification.  I’ll be using Edition 5.1 (ECMA-262) of the specification as the basis for the following discussion.

Execution Contexts

When a JavaScript function is executed, a construct referred to as an Execution Context is created.  The Execution Context is an abstract concept prescribed by the specification to track the execution progress of its associated code.  As an application runs, an initial Global Execution Context is created.  As each new function is created, new Execution Contexts are created which form an Execution Context stack.

There are three primary components prescribed for the Execution Context:

    1. The LexicalEnvironment

    2. The VariableEnvironment

    3. The ThisBinding

Only the LexicalEnvironment and VariableEnvironment components are relevant to the topic of closures, so I’ll exclude discussion of the ThisBinding.  (For information about how the ThisBinding is used, see sections 10.4.1.1, 10.4.2, and 10.4.3 of the ECMAScript Lanauage Specification.)

LexicalEnvironment

The LexicalEnvironment is used to resolve identifier references made by code associated with the execution context.  Conceptually, we can think of the LexicalEnvironment as an object containing the variables and formal parameters declared within the code associated by the current Execution Context.

A LexicalEnvironement itself is comprised of two components: An Environment Record, which is used to store identifier bindings for the Execution Context, and an outer reference which points to a LexicalEnvironment of the declaring Execution Context (which is null in the case of the Global Execution Context’s LexicalEnvironment outer reference).  This forms a chain of LexicalEnvironments, each maintaining a reference to the outer scope’s environment:

 

LexicalEnvironmentChain

 

VariableEnvironment

The VariableEnvironment is used to record the bindings created by  variables and function declarations within an execution context.  Upon reading that description, you may be thinking: “but I thought the LexicalEnvironment held the bindings for the current execution context”.  Technically, the VariableEnvironment contains the bindings of the variables and function declarations defined within an Execution Context and the LexicalEnvironment is used to resolve the bindings within the Execution Context.  Confused?  The answer to this seemingly incongruous approach is that, in most cases, the LexicalEnvironment and VariableEnvironment are references to the same entity.

The LexicalEnvironment and VariableEnvironment components are actually references to a LexicalEnvironment type.  When the JavaScript interpreter enters the code for a function, a new LexicalEnvironment instance is created and is assigned to both the LexicalEnvironment and VariableEnvironment references.  The variables and function declarations are then recorded to the VariableEnvironment reference.  When the LexicalEnvironment is used to resolve an identifier, any bindings created through the VariableEnvironment reference are available for resolution.

Identifier Resolution

As previously discussed, LexicalEnvironments have an outer reference which, except for the Global Execution Context’s LexicalEnvironment, points to a LexicalEnvironment record of the declaring Execution Context (i.e. a function block’s “parent” scope).  Functions contain an internal scope property (denoted as [[Scope]] by the ECMAScript specification) which is assigned a LexicalEnvironment from the declaring context.  In the case of function expressions (e.g. var doStuff = function() { …}), the [[Scope]] property is assigned to the declaring context’s LexicalEnvironment.  In the case of function declarations (e.g. function doStuff() { … }), the [[Scope]] property is assigned to the declaring context’s VariableEnvironment.  We’ll discuss the reasons for this disparity shortly, but for now let’s just focus on the fact that the function has a [[Scope]] which points to the environment in which is was created.  This is our pairing of a function with its referencing environment, which is to say, this is our closure. 

If we recall our previous conceptualization of a function paired with its environment, the JavaScript version of this conceptualization would look a little like this:

 

closure3

When resolving an identifier, the current LexicalEnvironment is passed to an abstract operation named GetIdentiferReference which checks the current LexicalEnvironment’s Environment Record for the requested identifier and if not found calls itself recursively with the LexicalEnvironment’s outer reference.  Each link of the chain is checked until the top of the chain is reached (the LexicalEnvironment of the Global Context) in which case the binding is resolved or a reference of undefined is returned.

A Distinction Without a Difference … Usually

As mentioned, the LexicalEnvironment and the VariableEnvironement references point to the same LexicalEnvironment instance in most cases.  The reason for maintaining these as separate references is to support the with statement.

The with statement facilitates block scope by using a supplied object as the Environment Record for a newly created LexicalEnvironment.  Consider the following example:

var x = {
    a: 1
};

var doSomething = function() {
    var a = 2;
    
    with(x) {
        console.log(a);
    };
};
doSomething(); // 1

In this code, while the doSomething function assigns the variable a the value of 2, the console.log function logs the value of 1 instead of 2.  What is happening here is that, for the enclosing block of code, the with statement is inserting a new LexicalEnvironment at the front of the chain with an Environment Record set to the object x.  When the code within the with statement executes, the first LexicalEnvironment to be checked will be the one created by the with statement whose Environment Record contains a binding of x with the value of 1.  Once the with statement exits, the LexicalEnvironment of the current Execution Context is restored to its previous state.

According to the ECMAScript specification, function expressions may be declared within a with statement, but not function declarations (though most implementations allow it with varied behavior).  Since function expressions may be declared, their declaration should form a closure based upon the declaring environment’s LexicalEnvironment because it is the LexicalEnvironement which might be changed by a with statement.  This is the reason why Execution Contexts are prescribed  two different LexicalEnvironment references and why function declarations and function expressions differ in which reference their [[Scope]] property is assigned upon function creation.

Conclusion

This concludes our exploration of closures in JavaScript.  While understanding the ECMAScript Language Specification in detail certainly isn’t necessary to have a working knowledge of closures, I find taking a peek under the covers now and again helps to broaden one’s understanding about a language and its concepts.

Tagged with:  

This is the fifth and final installment in the SOLID JavaScript series which explores the SOLID design principles within the context of the JavaScript language.  In this final installment, we’ll examine the Dependency Inversion Principle.

 

The Dependency Inversion Principle

The Dependency Inversion Principle relates to the stability and reusability of higher-level components within an application.  The principle states:

A. High-level modules should not depend on low-level modules.  Both should depend on abstractions.

B. Abstractions should not depend upon details.  Details should depend upon abstractions.

The primary concern of the Dependency Inversion Principle is to ensure that the main components of an application or framework remain decoupled from the ancillary components providing low-level implementation details.  This ensures that the important parts of an application or framework aren’t affected when the low level components need to change.

The first part of the principle concerns the method of coupling between high level modules and low level modules.  With traditional layered architecture, high level modules (components encapsulating the core business logic of the application) take dependencies upon low level modules (components providing infrastructure concerns).  When adhering to the Dependency Inversion Principle, this relationship is reversed (i.e. inverted).  Rather than high level modules being coupled to low level modules, low level modules are coupled to interfaces declared by the high level modules.  For example, given an application with persistence concerns, a traditional design might contain a core module which relies upon the API defined by a persistence module.  Refactoring toward the Dependency Inversion Principle, the persistence module would be modified to conform to an interface defined by the core module.

The second part of the Dependency Inversion Principle concerns the proper relationship between abstractions and details.  To understand this portion of the principle, it helps to consider its applicability to the language from whence the principle was conceived: the C++ language.

Unlike some statically typed languages, C++ doesn’t provide a language level construct for defining interfaces.  What it does provide is the separation of class definition from class implementation.  In C++, classes are defined using a header file which lists the member methods and variables of a class along with a source file which contains the implementation of any member methods.  Since any member variables and private methods are declared within the header file, it’s possible for classes intended to be used as abstractions to become dependent upon the implementation details of the class.  This is overcome by defining classes which only contain abstract methods (known in C++ as pure abstract base classes) to serve as interfaces for implementing classes.

DIP and JavaScript

As a dynamic language, JavaScript doesn’t require the use of abstractions to facilitate decoupling.  Therefore, the stipulation that abstractions shouldn’t depend upon details isn’t particularly relevant to JavaScript applications.  The stipulation that high level modules shouldn’t depend upon low level modules is, however, relevant.

When discussing the Dependency Inversion Principle in the context of statically-typed languages, the concern of coupling is both semantic and physical.  That is to say, if a high level module is coupled to a low level module, it is coupled both to the semantic interface as well as the physical definition of the interface defined within the low level module.  The implication is that high level module dependencies should be inverted both for dependencies upon 3rd party libraries as well as native low level modules.

To explain, consider a .Net application which might encapsulate useful high level modules which have a dependency upon a low level module providing persistence concerns. While the author is likely to have expressed a similar API for the persistence interface whether the DIP was adhered to or not, the high level module would not be capable of being reused in another application without bringing along the dependency upon the low level module where the persistence interface is defined.

In JavaScript, the applicability of the Dependency Inversion Principle is relevant only to the semantic coupling of high level modules to low level modules.  As such, adherence to the DIP can be achieved simply by expressing the semantic interface in terms of the application’s needs as opposed to coupling to the implicit interface defined by whatever implementation is chosen for a low level module.

To illustrate, consider the following example:

$.fn.trackMap = function(options) {
    var defaults = { 
        /* defaults */
    };
    options = $.extend({}, defaults, options);

    var mapOptions = {
        center: new google.maps.LatLng(options.latitude,options.longitude),
        zoom: 12,
        mapTypeId: google.maps.MapTypeId.ROADMAP
    },
        map = new google.maps.Map(this[0], mapOptions),
        pos = new google.maps.LatLng(options.latitude,options.longitude);

    var marker = new google.maps.Marker({
        position: pos,
        title: options.title,
        icon: options.icon
    });

    marker.setMap(map);

    options.feed.update(function(latitude, longitude) {
        marker.setMap(null);
        var newLatLng = new google.maps.LatLng(latitude, longitude);
        marker.position = newLatLng;
        marker.setMap(map);
        map.setCenter(newLatLng);
    });

    return this;
};

var updater = (function() {    
    // private properties

    return {
        update: function(callback) {
            updateMap = callback;
        }
    };
})();

$("#map_canvas").trackMap({
    latitude: 35.044640193770725,
    longitude: -89.98193264007568,
    icon: 'http://bit.ly/zjnGDe',
    title: 'Tracking Number: 12345',
    feed: updater
});

In this listing, we have a small library which converts a div target into an map used to show the current location of a item being tracked.  The trackMap function has two dependencies: the 3rd party Google Maps API and a location feed.  The responsibility of the feed object is to simply invoke a callback (supplied during the initialization process) with a new latitude and longitude position when the icon location should be updated.  The Google Maps API is used to do the actual rending of the map to the screen.

While the interface of the feed object may or may not have been designed in terms of the trackMap function, the fact that its role is simple and focused makes it easy to substitute different implementations.  Not so with the Google Maps dependency.  Since the trackMap function is semantically coupled to the Google Maps API, switching to a different mapping provider would require the trackMap function to be rewritten or an adapter to be written to adapt another mapping provider to Google’s specific interface.

To invert the semantic coupling to the Google Maps library, we need to redesign the trackMap function to have a semantic coupling to an implicit interface which abstractly represents the functionality needed by a mapping provider.  We would then need to implement an object which adapts this interface to the Google Maps API.  The following shows this alternate version of the trackMap function:

$.fn.trackMap = function(options) {
    var defaults = { 
        /* defaults */
    };

    options = $.extend({}, defaults, options);

    options.provider.showMap(
        this[0],
        options.latitude,
        options.longitude,
        options.icon,
        options.title);

    options.feed.update(function(latitude, longitude) {
        options.provider.updateMap(latitude, longitude);
    });

    return this;
};


$("#map_canvas").trackMap({
    latitude: 35.044640193770725,
    longitude: -89.98193264007568,
    icon: 'http://bit.ly/zjnGDe',
    title: 'Tracking Number: 12345',
    feed: updater,
    provider: trackMap.googleMapsProvider
});

In this version, we’ve redesigned the trackMap function to express its needs in terms of a generic mapping provider interface and have moved the implementation details out into a separate googleMapsProvider component which can be bundled as a separate JavaScript module.  Here’s our googleMapsProvider implementation:

trackMap.googleMapsProvider = (function() {
    var marker, map;

    return {
        showMap: function(element, latitude, longitude, icon, title) {
            var mapOptions = {
                center: new google.maps.LatLng(latitude, longitude),
                zoom: 12,
                mapTypeId: google.maps.MapTypeId.ROADMAP
            },
                pos = new google.maps.LatLng(latitude, longitude);

            map = new google.maps.Map(element, mapOptions);

            marker = new google.maps.Marker({
                position: pos,
                title: title,
                icon: icon
            });

            marker.setMap(map);
        },
        updateMap: function(latitude, longitude) {
            marker.setMap(null);
            var newLatLng = new google.maps.LatLng(latitude,longitude);
            marker.position = newLatLng;
            marker.setMap(map);
            map.setCenter(newLatLng);
        }
    };
})();

With these changes, our trackMap function is now more resilient to the changes that might occur to the Google Maps API and is capable of being reused with another mapping provider.  That is, as long as it’s API can be adapted to the needs of our application.

Whither Dependency Injection?

While not particularly related, the concept of Dependency Injection is often confused with the Dependency Inversion Principle due to a similarity in terminology.  For this reason, a discussion of the differences between the two concepts may prove helpful for some.

Dependency Injection is a specific form of Inversion of Control in which the concern being inverted is how a component obtains its dependencies.  When using Dependency Injection, dependencies are supplied to a component rather than the component obtaining the dependency by means of creating an instance of the dependency, requesting the dependency through a factory, requesting the dependency from a Service Locator, or any other means of initiation by the component itself.  Both the Dependency Inversion Principle and Dependency Injection are concerned with dependencies and both use the notion of inversion to contrast an alternate approach to a presumed standard approach.  However, the Dependency Inversion Principle isn’t concerned with how components obtains their dependencies, but with the decoupling of high level components from low level components.  In a sense, the Dependency Inversion Principle might be said to be another form of Inversion of Control where the concern being inverted is which module defines the interface.

Conclusion

This brings us to the end of our series.  While in the course of our examination we saw variations in how the SOLID design principles apply to JavaScript over other languages, each of the principles were shown to have some degree of applicability within JavaScript development.

Tagged with:  

This is the forth 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 Interface Segregation Principle.

 

The Interface Segregation Principle

The Interface Segregation Principle relates to the cohesion of interfaces within a system. The principle states:

Clients should not be forced to depend on methods they do not use.

When clients depend upon objects which contain methods used only by other clients, or are forced to implement unused methods with degenerate functionality (potentially leading to Liskov Substitution Principle violations), this can lead to fragile code. This occurs when an object serves as an implementation for a non-cohesive interface.

The Interface Segregation Principle is similar to the Single Responsibility Principle in that both deal with the cohesion of responsibilities. In fact, the ISP can be understood as the application of the SRP to an object’s public interface.

JavaScript Interfaces

So, what does this principle have to do with JavaScript? After all, JavaScript doesn’t have interfaces, right? If by interfaces we mean some abstract type provided by the language to establish contracts and enable decoupling, then such an assertion would be correct. However, JavaScript does have another type of interface. In the book Design Patterns – Elements of Reusable Object-Oriented Software, Gamma et al., we find the following definition of an interface:

Every operation declared by an object specifies the operation’s name, the objects it takes as parameters, and the operation’s return value. This is known as the operation’s signature. The set of all signatures defined by an object’s operations is called the interface to the object. An object’s interface characterizes the complete set of requests that can be sent to the object.

Regardless of whether a language provides a separate construct for representing interfaces or not, all objects have an implicit interface comprised of the set of public properties and methods of the object. For example, consider the following library:

var exampleBinder = {};
exampleBinder.modelObserver = (function() {
    /* private variables */
    return {
        observe: function(model) {
            /* code */
            return newModel;
        },
        onChange: function(callback) {
            /* code */
        }
    }
})();

exampleBinder.viewAdaptor = (function() {
    /* private variables */
    return {
        bind: function(model) {
            /* code */
        }
    }
})();

exampleBinder.bind = function(model) {
    /* private variables */
    exampleBinder.modelObserver.onChange(/* callback */);
    var om = exampleBinder.modelObserver.observe(model);
    exampleBinder.viewAdaptor.bind(om);
    return om;
};

This listing presents a library named exampleBinder whose purpose is to facilitate two-way data-binding. The public interface of the library is represented by the bind method. The responsibilities of change notification and view interaction have been separated into the objects modelObserver and viewAdaptor respectively to allow for alternate implementations. These objects represent the implementations of the interfaces expected by the bind method. Any object adhering to the semantic behavior represented by these interfaces may be substituted for the default implementations.

Though the JavaScript language may not provide interface types to aid in specifying the contract of an object, the object’s implicit interface still serves as a contract to clients within an application.

ISP and JavaScript

The following sections discuss some of the consequences to Interface Segregation Principle violations in JavaScript. As you’ll see, while the ISP is applicable to the design of JavaScript applications, the language features offer a little more resiliency to non-cohesive interfaces than in statically-typed languages.

Degenerate Implementations

In statically-typed languages, one issue that arises from violations of the ISP is the need to create degenerate implementations. In languages like Java and C#, all methods declared by an interface must be implemented. For cases where a particular interface is required, but only a subset of the behavior is relevant for a given usage scenario, the unused methods are generally stubbed out with empty implementations or with implementations which simply throw an exception indicating the method isn’t actually implemented. In JavaScript, cases where only a subset of an object’s interface is utilized doesn’t end up posing the same issues since a substituting object need only provide the expected properties to conform to the consumed portion of the object’s interface. Nevertheless, such implementations can still lead to Liskov Substitution Violations.

For instance, consider the following example:

var rectangle = {
    area: function() { 
        /* code */
    },
    draw: function() { 
        /* code */
    }
};

var geometryApplication = {
    getLargestRectangle: function(rectangles) { 
        /* code */
    }
};

var drawingApplication = {
    drawRectangles: function(rectangles) {
       /* code */
    }
};

While a substitute rectangle could be created with only an area() method in order to meet the needs of geometryApplication’s getLargestRectangle method, such an implementation would represent a LSP violation with respect to drawingApplication’s drawRectangles method.

Static Coupling

Another issue that arises in statically-typed languages is the issue of static coupling. In statically-typed languages, interfaces play a significant role in the design of loosely-coupled applications. In both static and dynamic languages, there are times when an object may need to collaborate with multiple clients (e.g. in cases where shared state may be required). For statically-typed languages, it’s considered a best practice for clients to interact with objects using Role Interfaces. This allows clients to interact with an object which may require the intersection of multiple roles as an implementation detail without coupling the client to unused behavior. In JavaScript, this isn’t an issue since objects are decoupled by virtue of the language’s dynamic capabilities.

Semantic Coupling

One consequence that’s equally relevant between JavaScript and statically-typed languages is the issue of semantic coupling. Semantic coupling is the interdependency that occurs when one portion of an object’s behavior is coupled to another. When an object’s interface specifies non-cohesive responsibilities, changes to adapt to the evolving needs of one client may inadvertently affect another client resulting from changes made to shared state or behavior. This is also one of the potential consequences to violating the Single Responsibly Principle, though this is typically viewed from the perspective of the impact non-cohesive behavior has on collaborating objects. From an ISP perspective, this consequence is extended to extensions via inheritance or object substitution.

Extensibility

Another important role interfaces play in JavaScript applications is in the area of extensibility. The most prevalent example of this can be seen in the use of callbacks where a function conforming to the expected interface is passed to a library to be invoked at some point in the future (e.g. upon a successful AJAX request). The Interface Segregation Principle becomes relevant when such interfaces require the implementation of an object with multiple properties and/or methods. When an interface begins to require the implementation of a significant number of methods, this makes working with the consuming library more difficult and is likely an indication that the interfaces represent non-cohesive responsibilities. This is often described as “fat” interfaces.

In summary, the dynamic capabilities of JavaScript leave us with a few less consequences to the occurrence of non-cohesive interfaces than with statically-typed languages, but the Interface Segregation Principle has its place in the design of JavaScript applications nonetheless.

Next time, we’ll take a look at the final principle in the SOLID acronym: The Dependency Inversion Principle.

Tagged with:  

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:  

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: