<?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet type="text/xsl" media="screen" href="/~d/styles/rss2full.xsl"?><?xml-stylesheet type="text/css" media="screen" href="http://feeds.feedburner.com/~d/styles/itemcontent.css"?><rss xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:wfw="http://wellformedweb.org/CommentAPI/" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:sy="http://purl.org/rss/1.0/modules/syndication/" xmlns:slash="http://purl.org/rss/1.0/modules/slash/" xmlns:series="http://unfoldingneurons.com/" xmlns:feedburner="http://rssnamespace.org/feedburner/ext/1.0" version="2.0">

<channel>
	<title>Aspiring Craftsman</title>
	
	<link>http://aspiringcraftsman.com</link>
	<description>pursuing well-crafted software</description>
	<lastBuildDate>Sat, 04 Feb 2012 21:01:44 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.3.1</generator>
		<atom10:link xmlns:atom10="http://www.w3.org/2005/Atom" rel="self" type="application/rss+xml" href="http://feeds.feedburner.com/AspiringCraftsman" /><feedburner:info uri="aspiringcraftsman" /><atom10:link xmlns:atom10="http://www.w3.org/2005/Atom" rel="hub" href="http://pubsubhubbub.appspot.com/" /><item>
		<title>SOLID JavaScript: The Dependency Inversion Principle</title>
		<link>http://feedproxy.google.com/~r/AspiringCraftsman/~3/dY0CGab_mw4/</link>
		<comments>http://aspiringcraftsman.com/2012/01/22/solid-javascript-the-dependency-inversion-principle/#comments</comments>
		<pubDate>Sun, 22 Jan 2012 01:13:21 +0000</pubDate>
		<dc:creator>derekgreer</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[Design Principles]]></category>
		<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[SOLID]]></category>

		<guid isPermaLink="false">http://aspiringcraftsman.com/?p=854</guid>
		<description><![CDATA[Series Table of Contents The Single Responsibility Principle The Open/Closed Principle The Liskov Substitution Principle The Interface Segregation Principle The Dependency Inversion Principle 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.&#160; In this final installment, we’ll examine the [...]]]></description>
			<content:encoded><![CDATA[<div style="border-bottom: black 1px solid; border-left: black 1px solid; float: right; margin-left: 4px; border-top: black 1px solid; border-right: black 1px solid" class="toc"><u>Series Table of Contents</u>     <br /><a href="http://aspiringcraftsman.com/2011/12/08/solid-javascript-single-responsibility-principle/">The Single Responsibility Principle</a>     <br /><a href="http://aspiringcraftsman.com/2011/12/19/solid-javascript-the-openclosed-principle/">The Open/Closed Principle</a>     <br /><a href="http://aspiringcraftsman.com/2011/12/31/solid-javascript-the-liskov-substitution-principle/">The Liskov Substitution Principle</a>     <br /><a href="http://aspiringcraftsman.com/2012/01/08/solid-javascript-the-interface-segregation-principle/">The Interface Segregation Principle</a>     <br />The Dependency Inversion Principle     <br /></div>  <p>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.&#160; In this final installment, we’ll examine the Dependency Inversion Principle.</p>  <div style="clear: both">&#160;</div>  <h2>The Dependency Inversion Principle</h2>  <p>The Dependency Inversion Principle relates to the stability and reusability of higher-level components within an application.&#160; The principle states:</p>  <blockquote>   <p>A. High-level modules should not depend on low-level modules.&#160; Both should depend on abstractions.</p>    <p>B. Abstractions should not depend upon details.&#160; Details should depend upon abstractions.</p> </blockquote>  <p>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.&#160; This ensures that the important parts of an application or framework aren’t affected when the low level components need to change.</p>  <p>The first part of the principle concerns the method of coupling between high level modules and low level modules.&#160; 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).&#160; When adhering to the Dependency Inversion Principle, this relationship is reversed (i.e. <em>inverted</em>).&#160; Rather than high level modules being coupled to low level modules, low level modules are coupled to interfaces declared by the high level modules.&#160; 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.&#160; Refactoring toward the Dependency Inversion Principle, the persistence module would be modified to conform to an interface defined by the core module.</p>  <p>The second part of the Dependency Inversion Principle concerns the proper relationship between abstractions and details.&#160; 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. </p>  <p>Unlike some statically typed languages, C++ doesn’t provide a language level construct for defining interfaces.&#160; What it does provide is the separation of class definition from class implementation.&#160; 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.&#160; 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.&#160; 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.</p>  <h2>DIP and JavaScript</h2>  <p>As a dynamic language, JavaScript doesn’t require the use of abstractions to facilitate decoupling.&#160; Therefore, the stipulation that <em>abstractions shouldn&#8217;t depend upon details</em> isn’t particularly relevant to JavaScript applications.&#160; The stipulation that <em>high level modules shouldn’t depend upon low level modules</em> is, however, relevant.</p>  <p>When discussing the Dependency Inversion Principle in the context of statically-typed languages, the concern of coupling is both <strong>semantic</strong> and <strong>physical</strong>.&#160; 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.&#160; 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. </p>  <p>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. </p>  <p>In JavaScript, the applicability of the Dependency Inversion Principle is relevant only to the semantic coupling of high level modules to low level modules.&#160; 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.</p>  <p>To illustrate, consider the following example:</p>  <pre class="prettyprint">$.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;
        }
    };
})();

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

<p>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.&#160; The trackMap function has two dependencies: the 3rd party Google Maps API and a location feed.&#160; 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.&#160; The Google Maps API is used to do the actual rending of the map to the screen. </p>

<p>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.&#160; Not so with the Google Maps dependency.&#160; 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.</p>

<p>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.&#160; We would then need to implement an object which adapts this interface to the Google Maps API.&#160; The following shows this alternate version of the trackMap function:</p>

<pre class="prettyprint">$.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;
};


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

<p>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.&#160; Here’s our googleMapsProvider implementation:</p>

<pre class="prettyprint">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);
        }
    };
})();</pre>

<p>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.&#160; That is, as long as it’s API can be adapted to the needs of our application.</p>

<h2>Whither Dependency Injection?</h2>

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

<p>Dependency Injection is a specific form of <a href="http://en.wikipedia.org/wiki/Inversion_of_control" target="_blank">Inversion of Control</a> in which the concern being inverted is how a component obtains its dependencies.&#160; 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.&#160; 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.&#160; 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.&#160; 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.</p>

<h2>Conclusion</h2>

<p>This brings us to the end of our series.&#160; 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.</p><img src="http://feeds.feedburner.com/~r/AspiringCraftsman/~4/dY0CGab_mw4" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://aspiringcraftsman.com/2012/01/22/solid-javascript-the-dependency-inversion-principle/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<series:name><![CDATA[SOLID JavaScript]]></series:name>
	<feedburner:origLink>http://aspiringcraftsman.com/2012/01/22/solid-javascript-the-dependency-inversion-principle/</feedburner:origLink></item>
		<item>
		<title>SOLID JavaScript: The Interface Segregation Principle</title>
		<link>http://feedproxy.google.com/~r/AspiringCraftsman/~3/NKGq9EwmbSA/</link>
		<comments>http://aspiringcraftsman.com/2012/01/08/solid-javascript-the-interface-segregation-principle/#comments</comments>
		<pubDate>Sun, 08 Jan 2012 03:58:35 +0000</pubDate>
		<dc:creator>derekgreer</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[Design Principles]]></category>
		<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[SOLID]]></category>

		<guid isPermaLink="false">http://aspiringcraftsman.com/?p=842</guid>
		<description><![CDATA[Series Table of Contents The Single Responsibility Principle The Open/Closed Principle The Liskov Substitution Principle The Interface Segregation Principle The Dependency Inversion Principle 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 [...]]]></description>
			<content:encoded><![CDATA[<div style="border-bottom: black 1px solid; border-left: black 1px solid; float: right; margin-left: 4px; border-top: black 1px solid; border-right: black 1px solid" class="toc"><u>Series Table of Contents</u>     <br /><a href="http://aspiringcraftsman.com/2011/12/08/solid-javascript-single-responsibility-principle/">The Single Responsibility Principle</a>     <br /><a href="http://aspiringcraftsman.com/2011/12/19/solid-javascript-the-openclosed-principle/">The Open/Closed Principle</a>     <br /><a href="http://aspiringcraftsman.com/2011/12/31/solid-javascript-the-liskov-substitution-principle/">The Liskov Substitution Principle</a>      <br />The Interface Segregation Principle     <br /><a href="http://aspiringcraftsman.com/2012/01/22/solid-javascript-the-dependency-inversion-principle/">The Dependency Inversion Principle</a>     <br /></div>  <p>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.</p>  <div style="clear: both">&#160;</div>  <h2>The Interface Segregation Principle </h2>  <p>The Interface Segregation Principle relates to the cohesion of interfaces within a system. The principle states: </p>  <blockquote>   <p>Clients should not be forced to depend on methods they do not use. </p> </blockquote>  <p>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 <a href="http://freshbrewedcode.com/derekgreer/2011/12/31/solid-javascript-the-liskov-substitution-principle/" target="_blank">Liskov Substitution Principle</a> violations), this can lead to fragile code. This occurs when an object serves as an implementation for a non-cohesive interface. </p>  <p>The Interface Segregation Principle is similar to the <a href="http://freshbrewedcode.com/derekgreer/2011/12/08/solid-javascript-single-responsibility-principle/" target="_blank">Single Responsibility Principle</a> 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. </p>  <h2>JavaScript Interfaces</h2>  <p>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 <a href="http://www.amazon.com/Design-Patterns-Elements-Reusable-Object-Oriented/dp/0201633612" target="_blank">Design Patterns &#8211; Elements of Reusable Object-Oriented Software</a>, Gamma et al., we find the following definition of an interface: </p>  <blockquote>   <p>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 <strong>signature</strong>. The set of all signatures defined by an object’s operations is called the <strong>interface</strong> to the object. An object’s interface characterizes the complete set of requests that can be sent to the object. </p> </blockquote>  <p>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: </p>  <pre class="prettyprint">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;
};</pre>

<p>This listing presents a library named <em>exampleBinder</em> 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 <em>modelObserver</em> and <em>viewAdaptor</em> respectively to allow for alternate implementations. These objects represent the implementations of the <strong>interfaces</strong> expected by the <em>bind</em> method. Any object adhering to the semantic behavior represented by these interfaces may be substituted for the default implementations. </p>

<p>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. </p>

<h2>ISP and JavaScript </h2>

<p>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. </p>

<h3>Degenerate Implementations</h3>

<p>In statically-typed languages, one issue that arises from violations of the ISP is the need to create <em>degenerate implementations</em>. 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. </p>

<p>For instance, consider the following example: </p>

<pre class="prettyprint">var rectangle = {
    area: function() { 
        /* code */
    },
    draw: function() { 
        /* code */
    }
};

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

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

<p>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. </p>

<h3>Static Coupling</h3>

<p>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 <a href="http://martinfowler.com/bliki/RoleInterface.html" target="_blank">Role Interfaces</a>. 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. </p>

<h3>Semantic Coupling</h3>

<p>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. </p>

<h3>Extensibility</h3>

<p>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. </p>

<p>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. </p>

<p>Next time, we’ll take a look at the final principle in the SOLID acronym: The Dependency Inversion Principle. </p><img src="http://feeds.feedburner.com/~r/AspiringCraftsman/~4/NKGq9EwmbSA" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://aspiringcraftsman.com/2012/01/08/solid-javascript-the-interface-segregation-principle/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<series:name><![CDATA[SOLID JavaScript]]></series:name>
	<feedburner:origLink>http://aspiringcraftsman.com/2012/01/08/solid-javascript-the-interface-segregation-principle/</feedburner:origLink></item>
		<item>
		<title>SOLID JavaScript: The Liskov Substitution Principle</title>
		<link>http://feedproxy.google.com/~r/AspiringCraftsman/~3/FUuCvXtkTYY/</link>
		<comments>http://aspiringcraftsman.com/2011/12/31/solid-javascript-the-liskov-substitution-principle/#comments</comments>
		<pubDate>Sat, 31 Dec 2011 16:00:32 +0000</pubDate>
		<dc:creator>derekgreer</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[Design Principles]]></category>
		<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[SOLID]]></category>

		<guid isPermaLink="false">http://www.aspiringcraftsman.com/?p=835</guid>
		<description><![CDATA[Series Table of Contents The Single Responsibility Principle The Open/Closed Principle The Liskov Substitution Principle The Interface Segregation Principle The Dependency Inversion Principle 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 [...]]]></description>
			<content:encoded><![CDATA[<div style="border-bottom: black 1px solid; border-left: black 1px solid; float: right; margin-left: 4px; border-top: black 1px solid; border-right: black 1px solid" class="toc"><u>Series Table of Contents</u>     <br /><a href="http://aspiringcraftsman.com/2011/12/08/solid-javascript-single-responsibility-principle/">The Single Responsibility Principle</a>     <br /><a href="http://aspiringcraftsman.com/2011/12/19/solid-javascript-the-openclosed-principle/">The Open/Closed Principle</a>     <br />The Liskov Substitution Principle       <br /></a><a href="http://aspiringcraftsman.com/2012/01/08/solid-javascript-the-interface-segregation-principle/">The Interface Segregation Principle</a>     <br /><a href="http://aspiringcraftsman.com/2012/01/22/solid-javascript-the-dependency-inversion-principle/">The Dependency Inversion Principle</a>     <br /></div>  <p>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.</p>  <div style="clear: both">&#160;</div>  <h2>The Liskov Substitution Principle</h2>  <p>The Liskov Substitution Principle relates to the interoperability of objects within an inheritance hierarchy.&#160; The principle states:</p>  <blockquote>   <p>Subtypes must be substitutable for their base types.</p> </blockquote>  <p>In object-oriented programming, inheritance provides a mechanism for sharing code within a hierarchy of related types.&#160; 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.&#160; To adhere to the Liskov Substitution Principle, a derived type should be semantically equivalent to the anticipated behavior of its base type.</p>  <p>To help illustrate, consider the following code:</p>  <pre class="prettyprint">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 &quot;parked&quot;;
        }
        else if (my.running &amp;&amp; my.speed) {
            return &quot;moving&quot;;
        }
        else if (my.running) {
            return &quot;idle&quot;;
        }
    };
}</pre>

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

<pre class="prettyprint">function FastVehicle(my) {
    my = my || {};
    
    var that = new Vehicle(my);
    that.accelerate = function() {
        my.speed += 3;
    };
    return that;
}</pre>

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

<pre class="prettyprint">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() != &quot;idle&quot;) {
        throw &quot;The vehicle is still moving!&quot;;
    }
    vehicle.stop();
    write(vehicle.state());
};</pre>

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

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

<p>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.</p>

<h2>Mitigating LSP Violations</h2>

<p>So, how can we avoid Liskov Substitution Principle Violations?&#160; Unfortunately, this isn’t always possible.&#160; To avoid LSP violations altogether, you would be faced with the difficult task of anticipating every single way a library might ever be used.&#160; 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.&#160; That said, there are a few strategies for heading off violations within your own code.</p>

<h3>Contracts</h3>

<p>One strategy for heading off the most egregious violations of the LSP is to use contracts.&#160; Contracts manifest in two main forms: executable specifications and error checking.&#160; With executable specifications, the contract for how a particular library is intended to be used is contained in a suite of automated tests.&#160; The second approach is to include error checking directly in the code itself in the form of preconditions, postconditions and invariant checks.&#160; This technique is known as <a href="http://en.wikipedia.org/wiki/Design_by_contract" target="_blank">Design By Contract</a>, a term coined by Bertrand Miller, creator of the Eiffel programming language.&#160; 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.</p>

<ul>
  <li>Always use Test-Driven Development to guide the design of your own code </li>

  <li>Optionally use Design By Contract techniques when designing reusable libraries </li>
</ul>

<p>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.&#160; 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.&#160; 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.</p>

<h3>Avoid Inheritance</h3>

<p>Another strategy for avoiding LSP violations is to minimize the use of inheritance where possible.&#160; In the book <a href="http://www.amazon.com/Design-Patterns-Elements-Reusable-Object-Oriented/dp/0201633612" target="_blank">Design Patterns &#8211; Elements of Reusable Object-Orineted Software</a> by. Gamma, et. al., we find the following advice:</p>

<blockquote>
  <p>Favor object composition over class inheritance</p>
</blockquote>

<p>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.&#160; When using inheritance, the derived types are coupled with their based types.&#160; This means that changes to the base type may inadvertently affect derived types.&#160; Additionally, composition tends to lead to smaller, more focused objects which are easier to maintain for static and dynamic languages alike.</p>

<h2>It About Behavior, Not Inheritance</h2>

<p>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.&#160; However, the essence of the Liskov Substitution Principle isn’t really concerned with inheritance, but behavioral compatibility.&#160; 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.&#160; 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.</p>

<p>To illustrate, let’s consider an example taken from the book <a href="http://www.amazon.com/Software-Development-Principles-Patterns-Practices/dp/0135974445">Agile Software Development, Principles, Patterns, &amp; Practices</a> by Robert C. Martin: the rectangle example.</p>

<h3>The Rectangle Example</h3>

<p>Consider that we have an application which uses a rectangle object defined as follows:</p>

<pre class="prettyprint">var rectangle = {
    length: 0,
    width: 0
};</pre>

<p>Later, it’s determined that the application also needs to work with a square.&#160; 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.&#160; 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:</p>

<pre class="prettyprint">var square = {};
(function() {
    var length = 0, width = 0;
    Object.defineProperty(square, &quot;length&quot;, {
        get: function() { return length; },
        set: function(value) { length = width = value; }
    });
    Object.defineProperty(square, &quot;width&quot;, {
        get: function() { return width; },
        set: function(value) { length = width = value; }
    });
})();</pre>

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

<pre class="prettyprint">var g = function(rectangle) {
    rectangle.length = 3;
    rectangle.width = 4;
    write(rectangle.length);
    write(rectangle.width);
    write(rectangle.length * rectangle.width);
};</pre>

<p>When the method is invoked with square, the product is 16 rather than the expected value of 12.&#160; Our square object violates the Liskov Substitution Principle with respect to the function g.&#160; 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.&#160; Correcting this situation would likely require a redesign of the shape objects and the consuming application.&#160; A more flexible approach might be to define rectangles and squares in terms of polygons.&#160; 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.</p>

<p>Next time, we’ll discuss the forth principle in the SOLID acronym: The Interface Segregation Principle.</p><img src="http://feeds.feedburner.com/~r/AspiringCraftsman/~4/FUuCvXtkTYY" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://aspiringcraftsman.com/2011/12/31/solid-javascript-the-liskov-substitution-principle/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<series:name><![CDATA[SOLID JavaScript]]></series:name>
	<feedburner:origLink>http://aspiringcraftsman.com/2011/12/31/solid-javascript-the-liskov-substitution-principle/</feedburner:origLink></item>
		<item>
		<title>SOLID JavaScript: The Open/Closed Principle</title>
		<link>http://feedproxy.google.com/~r/AspiringCraftsman/~3/PUt8Lg0UYpU/</link>
		<comments>http://aspiringcraftsman.com/2011/12/19/solid-javascript-the-openclosed-principle/#comments</comments>
		<pubDate>Mon, 19 Dec 2011 14:00:00 +0000</pubDate>
		<dc:creator>derekgreer</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[Design Principles]]></category>
		<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[SOLID]]></category>

		<guid isPermaLink="false">http://www.aspiringcraftsman.com/2011/12/19/solid-javascript-the-openclosed-principle/</guid>
		<description><![CDATA[Series Table of Contents The Single Responsibility Principle The Open/Closed Principle The Liskov Substitution Principle The Interface Segregation Principle The Dependency Inversion Principle 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. [...]]]></description>
			<content:encoded><![CDATA[<div style="border-bottom: black 1px solid; border-left: black 1px solid; float: right; margin-left: 4px; border-top: black 1px solid; border-right: black 1px solid" class="toc"><u>Series Table of Contents</u>     <br /><a href="http://aspiringcraftsman.com/2011/12/08/solid-javascript-single-responsibility-principle/">The Single Responsibility Principle</a>     <br />The Open/Closed Principle     <br /><a href="http://aspiringcraftsman.com/2011/12/31/solid-javascript-the-liskov-substitution-principle/">The Liskov Substitution Principle</a>     <br /><a href="http://aspiringcraftsman.com/2012/01/08/solid-javascript-the-interface-segregation-principle/">The Interface Segregation Principle</a>     <br /><a href="http://aspiringcraftsman.com/2012/01/22/solid-javascript-the-dependency-inversion-principle/">The Dependency Inversion Principle</a>     <br /></div>  <p>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.</p>  <div style="clear: both">&#160;</div>  <h2>The Open/Closed Principle </h2>  <p>The Open/Closed Principle relates to the extensibility of objects. The principle states:</p>  <blockquote>   <p><quote>Software entities (classes, modules, functions, etc.) should be open for extension but closed for modification.</quote></p> </blockquote>  <p>By <em>open for extension</em>, this principle means the ability for an entity to be adapted to meet the changing needs of an application. By <em>closed for modification</em>, 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.</p>  <p>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:</p>  <p><iframe style="width: 100%; height: 300px" src="http://jsfiddle.net/derekgreer/YeFcJ/embedded/" frameborder="0" allowfullscreen="allowfullscreen"></iframe></p>  <p>&#160;</p>  <div class="alt-display">&#160;</div>  <div class="alt-display">   <pre class="prettyprint">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 &lt; 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 &lt; 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);</pre>
</div>

<p>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.</p>

<p>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.</p>

<p>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 :</p>

<p><iframe style="width: 100%; height: 300px" src="http://jsfiddle.net/derekgreer/eNcVp/embedded/" frameborder="0" allowfullscreen="allowfullscreen"></iframe></p>

<p>&#160;</p>

<div class="alt-display">
  <pre class="prettyprint">function questionCreator(spec, my) {
    var that = {};

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

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

    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 &lt; 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 &lt; 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);</pre>
</div>

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

<p>First, we’ve factored out the code responsible for creating questions into a functional constructor named questionCreator. This constructor utilizes the <a href="http://en.wikipedia.org/wiki/Template_method_pattern" target="_blank">Template Method Pattern</a> for delegating the creation of each answer to extending types.</p>

<p>Second, we’ve replaced the use of the former constructor’s properties&#160; with a private spec property&#160; 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.</p>

<p>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 <a href="http://en.wikipedia.org/wiki/Strategy_pattern" target="_blank">Strategy Pattern</a>) which extends the questionCreator object using <em>differential inheritance</em>.</p>

<p>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.</p>

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

<p>Next time, we’ll discuss the third principle in the SOLID acronym: The Liskov Substitution Principle.</p><img src="http://feeds.feedburner.com/~r/AspiringCraftsman/~4/PUt8Lg0UYpU" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://aspiringcraftsman.com/2011/12/19/solid-javascript-the-openclosed-principle/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<series:name><![CDATA[SOLID JavaScript]]></series:name>
	<feedburner:origLink>http://aspiringcraftsman.com/2011/12/19/solid-javascript-the-openclosed-principle/</feedburner:origLink></item>
		<item>
		<title>Acronyms and Ubiquitous Language</title>
		<link>http://feedproxy.google.com/~r/AspiringCraftsman/~3/vlKWInaP9t8/</link>
		<comments>http://aspiringcraftsman.com/2011/12/11/acronyms-and-ubiquitous-language/#comments</comments>
		<pubDate>Sun, 11 Dec 2011 18:20:31 +0000</pubDate>
		<dc:creator>derekgreer</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[Acronyms]]></category>
		<category><![CDATA[Ubiquitous Language]]></category>

		<guid isPermaLink="false">http://www.aspiringcraftsman.com/2011/12/11/acronyms-and-ubiquitous-language/</guid>
		<description><![CDATA[Acronyms are often employed within organizations as a way to abbreviate frequently used phrases in an attempt to expedite communication.&#160; Unfortunately, their use often does the exact opposite.&#160; Many programming language style guides discourage the use of acronyms.&#160; For instance, here’s what the .Net Framework General Naming Conventions has to say on the use of [...]]]></description>
			<content:encoded><![CDATA[<p>Acronyms are often employed within organizations as a way to abbreviate frequently used phrases in an attempt to expedite communication.&#160; Unfortunately, their use often does the exact opposite.&#160; Many programming language style guides discourage the use of acronyms.&#160; For instance, here’s what the .Net Framework <a href="http://msdn.microsoft.com/en-us/library/ms229045.aspx">General Naming Conventions</a> has to say on the use of acronyms: </p>  <blockquote>   <p><strong>Do not use any acronyms that are not widely accepted, and then only when necessary. </strong></p> </blockquote>  <p>The reasoning for this is that acronyms tend to present a barrier to understanding rather than their intended goal of expediting communication.&#160; When used in conversation, if you’re confronted with an unfamiliar acronym then you at least have an opportunity to ask “<em>What does XYZ stand for?</em>”, 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. </p>  <p>Some might ask: “<em>But what do we do when acronyms are a deeply rooted part of the business’s day-to-day language?</em>” </p>  <p>The use of a common language between developers and the business is referred to in Domain Driven Design as “<em>Ubiquitous Language</em>”.&#160; The book <a href="http://www.amazon.com/Domain-Driven-Design-Tackling-Complexity-Software/dp/0321125215/ref=sr_1_1?ie=UTF8&amp;qid=1323619169&amp;sr=8-1">Domain-Driven Design</a> by Eric Evans has this to say concerning the use of a shared language with the business: </p>  <blockquote>   <p>A project faces serious problems when its language is fractured.&#160; Domain experts use their jargon while technical team members have their own language tuned for discussing the domain in terms of design. </p>    <p>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).&#160; 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. </p>    <p>Translation blunts communication and makes knowledge crunching anemic.&#160; Yet none of these dialects can be a common language because none serves all needs. </p>    <p>… </p>    <p>Therefore: </p>    <p>Use the model as the backbone of a language.&#160; Commit the team to exercising that language relentlessly in all communication within the team and in the code.&#160; Use the same language in diagrams, written, and especially speech. </p>    <p>Iron out difficulties by experimenting with alternative expressions, which reflect alternative models.&#160; The refactor the code, renaming classes, methods, and modules to conform to the new model.&#160; Resolve confusion over terms in conversation, in just the way we come to agree on the meaning of ordinary words. </p>    <p>Recognize that a change in the UBIQUITOUS LANGUAGE is a change to the model. </p>    <p>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.</p> </blockquote>  <p>&#160; </p>  <p>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. </p>  <p>First, the avocation of a Ubiquitous Language is first and foremost to facilitate communication and understanding.&#160; 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.&#160; That said, if the Ubiquitous Language isn’t promoting communication and understanding then you’re doing it wrong. </p>  <p>&#160; </p>  <p align="center"><a href="http://www.aspiringcraftsman.com/wp-content/uploads/2011/12/cargo_cult_3.jpg"><img style="background-image: none; border-right-width: 0px; padding-left: 0px; padding-right: 0px; display: block; float: none; border-top-width: 0px; border-bottom-width: 0px; margin-left: auto; border-left-width: 0px; margin-right: auto; padding-top: 0px" title="cargo_cult_3" border="0" alt="cargo_cult_3" src="http://www.aspiringcraftsman.com/wp-content/uploads/2011/12/cargo_cult_3_thumb.jpg" width="500" height="256" /></a>&#160; <strong>Other people doing it wrong</strong>&#160;&#160; </p>  <p>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.&#160; Expansion of business acronyms within the code doesn’t necessarily constitute a departure from the Ubiquitous Language. </p>  <p>Third, the formation of the Ubiquitous Language is a two-way street.&#160; 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.&#160; 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. </p>  <p>That said, there are times when the use of business-specific acronyms may be appropriate.&#160; 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.&#160; For example, imagine your company has won a bid to write an application for the <a href="http://en.wikipedia.org/wiki/Ultimate_Fighting_Championship">Ultimate Fighting Championship</a> company to keep track of tournament brackets for Pay Per View events.&#160; For such an application, it would be completely appropriate to use the commonly used abbreviation for the company: UFC.&#160;&#160; </p>  <p>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. </p>  <p>I once worked at a company whose primary contract was with the United States Military.&#160; If you’ve never been exposed to military jargon before, I can tell you they take the use of acronyms to the extreme.&#160; The use of acronyms were littered throughout the code which made understanding the domain difficult for all.&#160; 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.&#160; 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.&#160; Recommendations to stop using acronyms were met with objections that the team should continue using them because it was the “Ubiquitous Language”.&#160; 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.&#160; Unfortunately, these choices among others lead to low quality and a high turn over rate among the development staff. </p>  <p>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.&#160; 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. </p><img src="http://feeds.feedburner.com/~r/AspiringCraftsman/~4/vlKWInaP9t8" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://aspiringcraftsman.com/2011/12/11/acronyms-and-ubiquitous-language/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		<feedburner:origLink>http://aspiringcraftsman.com/2011/12/11/acronyms-and-ubiquitous-language/</feedburner:origLink></item>
		<item>
		<title>SOLID JavaScript: The Single Responsibility Principle</title>
		<link>http://feedproxy.google.com/~r/AspiringCraftsman/~3/AJht-RBMboU/</link>
		<comments>http://aspiringcraftsman.com/2011/12/08/solid-javascript-single-responsibility-principle/#comments</comments>
		<pubDate>Thu, 08 Dec 2011 17:54:00 +0000</pubDate>
		<dc:creator>derekgreer</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[Design Principles]]></category>
		<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[SOLID]]></category>

		<guid isPermaLink="false">http://www.aspiringcraftsman.com/?p=821</guid>
		<description><![CDATA[Series Table of Contents The Single Responsibility Principle The Open/Closed Principle The Liskov Substitution Principle The Interface Segregation Principle The Dependency Inversion Principle This is the first installment in the SOLID JavaScript series which will explore the SOLID design principles within the context of the JavaScript language.&#160; In this first installment, we’ll take a look [...]]]></description>
			<content:encoded><![CDATA[<div style="border-bottom: black 1px solid; border-left: black 1px solid; float: right; border-top: black 1px solid; border-right: black 1px solid" class="toc"><u>Series Table of Contents</u>     <br />The Single Responsibility Principle     <br /><a href="http://aspiringcraftsman.com/2011/12/19/solid-javascript-the-openclosed-principle/">The Open/Closed Principle</a>     <br /><a href="http://aspiringcraftsman.com/2011/12/31/solid-javascript-the-liskov-substitution-principle/">The Liskov Substitution Principle</a>     <br /><a href="http://aspiringcraftsman.com/2012/01/08/solid-javascript-the-interface-segregation-principle/">The Interface Segregation Principle</a>     <br /><a href="http://aspiringcraftsman.com/2012/01/22/solid-javascript-the-dependency-inversion-principle/">The Dependency Inversion Principle</a>     <br /></div>  <p>This is the first installment in the SOLID JavaScript series which will explore the SOLID design principles within the context of the JavaScript language.&#160; 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.</p>  <div style="clear: both">&#160;</div>  <h2>The SOLID Design Principles and JavaScript</h2>  <p>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.&#160;&#160;&#160; These principles are as follows:</p>  <ul>   <li>The Single Responsibility Principle </li>    <li>The Open/Closed Principle </li>    <li>The Liskov Substitution Principle </li>    <li>The Interface Segregation Principle </li>    <li>The Dependency Inversion Principle </li> </ul>  <p>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.&#160; This article will cover the first of these principles: <a href="http://en.wikipedia.org/wiki/Single_responsibility_principle">The Single Responsibility Principle</a>.</p>  <h2>The Single Responsibility Principle</h2>  <p>The Single Responsibility Principle relates to the functional relatedness of the elements of a module.&#160; The principle states:</p>  <blockquote>   <p>A class should have only one reason to change</p> </blockquote>  <p>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.&#160; More simply, an object’s definition should only have to be modified due to changes to a single responsibility within the system.</p>  <p>Adherence to the Single Responsibility Principle helps to improve maintainability by limiting the responsibilities of an object to those which change for related reasons.&#160; When an object encapsulates multiple responsibilities, changes to the object for one of the responsibilities can negatively impact the others.&#160; By decoupling such responsibilities, we can create code that is more resilient to change.</p>  <p>But how do we identify whether a given set of behaviors constitutes a single responsibility?&#160; Would grouping all string manipulation into a single object be a single responsibility?&#160; How about grouping together all the service calls made within an application?&#160; Without an established approach to making these determinations, adhering to the Single Responsibility can be a bit perplexing.</p>  <h2>Object Role Stereotypes</h2>  <p>One approach which can aid in the organization of behavior within a system is the use of <em>Object Role Stereotypes</em>.&#160; Object Role Stereotypes are a set of general, pre-established roles which commonly occur across object-oriented architectures.&#160; 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.</p>  <p>The concept of Object Role Stereotypes is discussed in the book <a href="http://www.amazon.com/Object-Design-Roles-Responsibilities-Collaborations/dp/0201379430">Object Design: Roles, Responsibilies, and Collaborations</a> by Rebecca Wirfs-Brock and Alan McKean.&#160; The book presents the following stereotypes::</p>  <ul>   <li><strong>Information holder</strong> – an object designed to know certain information and provide that information to other objects. </li>    <li><strong>Structurer</strong> – an object that maintains relationships between objects and information about those relationships. </li>    <li><strong>Service provider</strong> – an object that performs specific work and offers services to others on demand. </li>    <li><strong>Controller</strong> – an object designed to make decisions and control a complex task. </li>    <li><strong>Coordinator</strong> – an object that doesn’t make many decisions but, in a rote or mechanical way, delegates work to other objects. </li>    <li><strong>Interfacer</strong> – an object that transforms information or requests between distinct parts of a system. </li> </ul>  <p>While not prescriptive, this set of role stereotypes provides an excellent mental framework for aiding in the software design process.&#160; Once you have an established&#160; 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.</p>  <h2>Single Responsibility Principle Example</h2>  <p>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:</p>  <p><iframe height="400" src="http://jsfiddle.net/derekgreer/Yvhwy/embedded/" frameborder="0" width="600"></iframe></p>  <div class="alt-display">   <pre class="prettyprint">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, &quot;Star Wars Lego Ship&quot;),
    new Product(2, &quot;Barbie Doll&quot;),
    new Product(3, &quot;Remote Control Airplane&quot;)],
    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 = $('&lt;li&gt;&lt;/li&gt;')
            .html(product.getDescription())
            .attr('id-cart', product.getId())
            .appendTo(&quot;#cart&quot;);
    }

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

<p>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:</p>

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

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

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

<p>Let’s break these three responsibilities out into their own objects:</p>

<p>&#160;</p>

<p><iframe height="400" src="http://jsfiddle.net/derekgreer/RPuNx/embedded/" frameborder="0" width="600"></iframe></p>

<div class="alt-display">
  <pre class="prettyprint">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 &lt; 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(&quot;itemAdded&quot;, item);
    };
}

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

var cartController = (function(cart) {
    eventAggregator.subscribe(&quot;productSelected&quot;, 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, &quot;Star Wars Lego Ship&quot;),
    new Product(2, &quot;Barbie Doll&quot;),
    new Product(3, &quot;Remote Control Airplane&quot;)];

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

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

<p>In our revised design, we’ve removed our anonymous function and replace it with objects to coordinate each of the separate set of responsibilities.&#160; 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.&#160; We also introduced an <a href="http://martinfowler.com/eaaDev/EventAggregator.html">Event Aggregator</a> to facilitate communication between the objects in a loosely-coupled way.&#160; 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.</p>

<p>Next time, we’ll discuss the next principle in the SOLID acronym: The Open/Closed Principle.</p><img src="http://feeds.feedburner.com/~r/AspiringCraftsman/~4/AJht-RBMboU" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://aspiringcraftsman.com/2011/12/08/solid-javascript-single-responsibility-principle/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		<feedburner:origLink>http://aspiringcraftsman.com/2011/12/08/solid-javascript-single-responsibility-principle/</feedburner:origLink></item>
		<item>
		<title>Adding JSLint To Your Build</title>
		<link>http://feedproxy.google.com/~r/AspiringCraftsman/~3/eWsHsq6T2d4/</link>
		<comments>http://aspiringcraftsman.com/2011/12/02/adding-jslint-to-your-build/#comments</comments>
		<pubDate>Fri, 02 Dec 2011 05:30:32 +0000</pubDate>
		<dc:creator>derekgreer</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[JSLint]]></category>
		<category><![CDATA[Node]]></category>
		<category><![CDATA[Rake]]></category>

		<guid isPermaLink="false">http://www.aspiringcraftsman.com/?p=818</guid>
		<description><![CDATA[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.&#160; 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, [...]]]></description>
			<content:encoded><![CDATA[<p><a href="http://jslint.com/">JSLint</a>, the popular JavaScript static code analysis tool written by Douglas Crockford, can fairly easily be incorporated into your builds through the use of <a href="http://nodejs.org/">node</a> and the <a href="https://github.com/reid/node-jslint">jslint node module</a>.&#160; The following steps will show you how to add JSLint to an existing rake build:</p>  <h2>Step 1: Install Node</h2>  <p>If you don’t already have it, go download and install node from <a href="http://nodejs.org/">http://nodejs.org/</a>.</p>  <h2>Step 2: Add JSLint Method</h2>  <p>The following jslint method uses the <a href="http://npmjs.org/">Node Package Manager</a> (npm) to install the jslint module into the current folder if it does not already exist.&#160; If node or npm are not found in the execution path then an error message is printed and the method simply returns.&#160; The method uses a hash config parameter for its parameters.</p>  <pre class="prettyprint">def jslint(config)
    tool = 'jslint'
    flags = config['flags'] || ''

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

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

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

    scripts = config['scripts'] || [&quot;&quot;]
    sh &quot;\&quot;#{node}\&quot; node_modules/#{tool}/bin/#{tool}.js #{flags} #{scripts}&quot;
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 = &quot;#{path}#{sep}#{cmd}#{ext}&quot;
        return exe if File.executable? exe
    }
    end
    return nil
end</pre>

<h2>Step 3: Add a Lint Task</h2>

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

<pre class="prettyprint">    task :lint do
        config = { 'flags'   =&gt; '--white',
                   'scripts' =&gt; FileList.new(&quot;src/**/app/*.js&quot;) }
        jslint(config)
    end</pre>

<p>That’s all you need.&#160; Now you can run “rake lint” or tie this into to your existing process as you see fit.&#160; Enjoy!</p><img src="http://feeds.feedburner.com/~r/AspiringCraftsman/~4/eWsHsq6T2d4" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://aspiringcraftsman.com/2011/12/02/adding-jslint-to-your-build/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		<feedburner:origLink>http://aspiringcraftsman.com/2011/12/02/adding-jslint-to-your-build/</feedburner:origLink></item>
		<item>
		<title>Getting Started With RequireJS</title>
		<link>http://feedproxy.google.com/~r/AspiringCraftsman/~3/D1K3I8TbE0c/</link>
		<comments>http://aspiringcraftsman.com/2011/11/28/getting-started-with-requirejs/#comments</comments>
		<pubDate>Mon, 28 Nov 2011 07:00:22 +0000</pubDate>
		<dc:creator>derekgreer</dc:creator>
				<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://www.aspiringcraftsman.com/?p=815</guid>
		<description><![CDATA[Have you ever found yourself struggling to find your bearings in an unorganized and unfamiliar JavaScript code-base? Without a systematic method of organizing your code, Javascript can get complex pretty quickly. One of the drawbacks to the JavaScript language is its lack of native module support. This omission can be mitigated to some degree through [...]]]></description>
			<content:encoded><![CDATA[<p>Have you ever found yourself struggling to find your bearings in an unorganized and unfamiliar JavaScript code-base?  Without a systematic method of organizing your code, Javascript can get complex pretty quickly.</p>

<p>One of the drawbacks to the JavaScript language is its lack of native module support.  This omission can be mitigated to some degree through the use of the Module Pattern in conjunction with the separation of modules into separate script files.</p>

<p>The following is a simple example demonstrating how a JavaScript code base can be organized into separate files in conjunction with the Module Pattern.</p>

<p>Consider a project with the following folder structure:</p>

project-directory/
project.html
scripts/
customerModule.js
orderModule.js
projectModule.js



<p>In this example, project.html depends upon three modules: projectModule, customerModule, and orderModule.  The modules are included using script tags for each file:</p>
<pre class="prettyprint">
<code>
&lt;!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
        "http://www.w3.org/TR/html4/loose.dtd"&gt;
&lt;html&gt;
&lt;head&gt;
    &lt;title&gt;Example&lt;/title&gt;
    &lt;script language="JavaScript1.5" type="text/javascript" src="scripts/customerModuleModule.js"&gt;&lt;/script&gt;
    &lt;script language="JavaScript1.5" type="text/javascript" src="scripts/orderModule.js"&gt;&lt;/script&gt;
    &lt;script language="JavaScript1.5" type="text/javascript" src="scripts/projectModule.js"&gt;v/script&gt;
&lt;/head&gt;
&lt;body&gt;
&lt;!-- body here --&gt;
&lt;/body&gt;
&lt;/html&gt;
</code>
</pre>

<p>The customerModule.js file defines a global customerModule which is assigned to an anonymous object containing a getCustomers function through the use of a self-executing anonymous function:</p>

<pre class="prettyprint">
var customerModule = function () {
    return {
        getCustomers: function() {
            // do something to get customers ...
        }
    }
}();
</pre>

<p>The orderModule.js file follows the same pattern to define a global orderModule object:</p>
<pre class="prettyprint">
var orderModule = function () {
    return {
        getOrders: function() {
            // do something to get orders ...
        }
    }
}();
</pre>

<p>The projectModule.js file for contains a self-executing anonymous function expression initialized using the the customerModule and orderModule:</p>

<pre class="prettyprint">
(function(c, o) {
       
    var customers = c.getCustomers();
    // do something with customers ...
    
    var orders = o.getOrders();
    // do something with orders ...

}(customerModule, orderModule));
</pre>

<p>Organizing Javascript using this approach can significantly improve the maintainability of a code base, but this approach does have a few drawbacks.</p>

<p>First, each of the modules required by the project.html file have to be declared within a script tag.  Generally, some of the referenced scripts will be specific to the project while others will be transitive dependencies providing supporting infrastructure needs (i.e. jquery, knockout, underscore, etc.).  As a code base evolves over time, it may be difficult to know which of these dependencies are still used. Referencing required dependencies in a file other than the requiring module can also make it more difficult to reuse those modules across projects. </p>

<p>Second, this approach requires that the script tags be declared in a particular order.  In the previous example, the customerModule and orderModule variables have to be defined prior to the definition of the projectModule.</p>

<p>Third, this approach pollutes the global name space by defining the module variables globally (though, this problem can be reduced to some degree by the use of a single application namespace).</p>

<p>While not horrible drawbacks, there is an alternative.</p>

<h2>RequireJS</h2>

<p><a href="http://requirejs.org">RequireJS</a> is an implementation of the <a href="https://github.com/amdjs/amdjs-api/wiki/AMD">Asynchronous Module Definition</a> (AMD) specification which defines a mechanism for loading modules asynchronously along with a declaration of dependencies by each module.</p>

<p>Let’s consider our previous example implemented using RequireJS.  With this implementation, we’ll replace projectModule.js with a main.js which will serve as our main script entry point.  With this change, our project.html file only requires the use of a single script tag to declare the main entry point:</p>

<pre class="prettyprint">
&lt;!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
        "http://www.w3.org/TR/html4/loose.dtd">
&lt;html>
&lt;head>
    &lt;title>Example Application&lt;/title>
    &lt;script data-main="scripts/main" src="scripts/require.js">&lt;/script>
&lt;/head>
&lt;body>
&lt;h1>Example Application&lt;/h1>
&lt;/body>
&lt;/html>
</pre>

<p>Note the data-main attribute which is used by require.js as an indicator of the initial script to load.</p>

<p>The main.js script contains the following:</p>

<pre class="prettyprint">
require(["customerModule", "orderModule"], function(c, o) {
    
    var customers = c.getCustomers();
    // do something with customers ...

    var orders = o.getOrders();
    // do something with orders ...    
});
</pre>

<p>In main.js, the require method is used to first define the module dependencies as an array and a callback function once the modules have been loaded.</p>

<p>The customerModule.js file is modified to the following:</p>

<pre class="prettyprint">
define(function() {
    return {
         getCustomers: function() {
            // do something to get customers ...
        }
    }
});
</pre>

<p>Similarly, the orderModule.js file is modified to the following:</p>

<pre class="prettyprint">
define(function() {
    return {
         getOrders: function() {
            // do something to get orders ...
        }
    }
});
</pre>

<p>Rather than defining objects on the global namespace, the define function is used to define the customer and order modules.</p>

<p>Pretty simple, eh?  In addition to these rather simple use cases, RequireJS also supports more advance scenarios such as adaptation to <a href="http://www.commonjs.org/">CommonJS</a> modules (the module specification used by node.js), dealing with circular dependencies, support for internationalization, and more.  RequireJS also provides an optimizer which, among other things, combines and minifies your scripts for optimal performance.</p>

<p>For a more in-depth look at the topic of writing modular JavaScript, I suggest checking out an excellent article entitled <a href="http://addyosmani.com/writing-modular-js/">Writing Modular JavaScript With AMD, CommonJS &#038; ES Harmony</a>.</p><img src="http://feeds.feedburner.com/~r/AspiringCraftsman/~4/D1K3I8TbE0c" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://aspiringcraftsman.com/2011/11/28/getting-started-with-requirejs/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		<feedburner:origLink>http://aspiringcraftsman.com/2011/11/28/getting-started-with-requirejs/</feedburner:origLink></item>
		<item>
		<title>How To Produce Bug-Free Software</title>
		<link>http://feedproxy.google.com/~r/AspiringCraftsman/~3/FZSHILYkyDI/</link>
		<comments>http://aspiringcraftsman.com/2011/10/18/how-to-produce-bug-free-software/#comments</comments>
		<pubDate>Tue, 18 Oct 2011 13:20:00 +0000</pubDate>
		<dc:creator>derekgreer</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[Testing]]></category>

		<guid isPermaLink="false">http://www.aspiringcraftsman.com/?p=773</guid>
		<description><![CDATA[Many are resigned to the fact that all software is destined to contain some “bugs”, but did you know it’s possible (and arguably pretty easy) to always produce “bug-free” software?&#160; In this article, I’ll explain how. Terms To begin, let’s consider the definition of a software “bug”.&#160; Merriam-Webster’s dictionary defines a bug as follows: bug [...]]]></description>
			<content:encoded><![CDATA[<p>Many are resigned to the fact that all software is destined to contain some “bugs”, but did you know it’s possible (and arguably pretty easy) to always produce “bug-free” software?&#160; In this article, I’ll explain how.</p>  <h2>Terms</h2>  <p>To begin, let’s consider the definition of a software “bug”.&#160; Merriam-Webster’s dictionary defines a bug as follows:</p>  <blockquote>   <p><strong>bug</strong> &#8211; “an unexpected defect, fault, flaw, or imperfection”</p> </blockquote>  <p>This definition may be fine for casual use, but you certainly wouldn&#8217;t want to use this as the basis for any contractual obligations.&#160; The problem with this definition is that it lacks objectivity.&#160; The terms ‘defect’, ‘fault’, ‘flaw’, and ‘imperfection’ are all relative terms, but what are they relative to?&#160; Based upon this definition, these designations are made based upon some deviation from an unstated set of expectations, but upon what are these expectations based?&#160; What if different expectations are held independently by your users, testing groups, mangers, product owners and yourself?&#160; Should all differences between any of these expectations and the actual behavior be considered bugs?&#160; Clearly a more objective definition is needed if we are to ever be capable of producing bug-free software.</p>  <p>To this end, I submit the following definition:</p>  <blockquote>   <p><strong>bug</strong> &#8211; “a deviation from an objective set of specifications set forth at the outset of a development effort.”</p> </blockquote>  <p>In order for a development team to consistently write bug-free software, an objective set of specifications must exist by which the software may be measured by prior to delivery.&#160; Unfortunately, such specifications are rarely created … not in any objective form.&#160; This problem often stems from the application of an incorrect process control model.</p>  <h2>Process Control Theory</h2>  <p>There are two primary approaches to controlling processes:&#160; The<a href="http://en.wikipedia.org/wiki/Defined_process"> defined process control model</a> and the<a href="http://en.wikipedia.org/wiki/Empirical_process_(process_control_model)"> empirical process control model</a>.</p>  <p>The <strong>defined process control model</strong> is applicable to processes where all the work involved is completely understood at the outset of production and the result of each stage of production is predictable and repeatable.&#160; An assembly-line production of automobiles is a example where a defined process model might be applied.</p>  <p>The <strong>empirical process control model</strong> is applicable to processes where the product of the work has a high degree of unpredictability and/or the product’s specifications aren’t completely defined and understood at the outset of production.&#160; This model is characterized by the use of frequent inspection and adaptation during the production process.&#160; The research and initial formulation of medications to treat diseases are examples where an empirical process control model would be applied.</p>  <p>Unfortunately, it’s been the defined process control model which has been the predominate approach to software development throughout its history.&#160; The most prevalent manifestation of the defined process control model has been the&#160; <a href="http://en.wikipedia.org/wiki/Waterfall_model">Waterfall model</a>, a process control model characterized by sequential stages of development which include requirements gathering, analysis, design, implementation, and verification.&#160; Fortunately some within the industry have come to understand that software development requires an empirical process control model and the rest of the industry appears to be slowly coming around<sup>1</sup>.</p>  <p>In the book <em>Agile Software Development with Scrum</em>, Ken Schwaber discusses some feedback he received upon consulting with process theory experts concerning his lack of success in applying commercial methodologies within his company.&#160; The following is his account of this feedback:</p>  <blockquote>   <p><em>They inspected the systems development processes that I brought them.&#160; I have rarely provided a group with so much laughter.&#160; They were amazed and appalled that my industry, systems development, was trying to do its work using a completely inappropriate process control model.&#160; They said systems development had so much complexity and unpredictability that it had to be managed by a process control model they referred to as “empirical.”&#160; They said this was nothing new, and all complex processes that weren’t completely understood required the empirical model.&#160; They helped me go through a book that is the Bible of industrial process control theory, Process Dynamics, Modeling and Control [Tunde] to understand why I was off track. </em></p>    <p><em>In a nutshell, there are two major approaches to controlling any process.&#160; The “defined” process control model requires that every piece of work be completely understood.&#160; Given a well-defined set of inputs, the same outputs are generated every time. … Tunde told me the empirical model of process, on the other hand, expects the unexpected.&#160; It provides and exercises control through frequent inspection and adaptation for processes that are imperfectly defined and generate unpredictable and unrepeatable outputs.</em></p> </blockquote>  <p>When software development is correctly understood to be an inherently empirical process in need of frequent inspection and adjustment, many naturally conclude that an objective, repeatable inspection process is need.&#160; Enter executable specifications &#8230;</p>  <h2>Executable Specifications</h2>  <p>In the<a href="http://en.wikipedia.org/wiki/Scientific_method"> Scientific Method</a>, empirical data is collected through repeatable processes to guard against mistakes or confusion by experimenters.&#160; To ensure our software is defect-free, we need to employ a similar set of repeatable processes.&#160; Not only should such processes guard against mistakes or confusion during the development effort, but such processes can and should themselves be the agreed-upon specifications.&#160; In the software development world, these sets of controlled processes can be fulfilled by Executable Specifications.&#160; </p>  <p>Simply, executable specifications are a set of automated tests which encapsulate the context, actions, and observable outcomes defined and agreed upon between a customer and a development team. Without such specifications, no objective measure exists by which to weigh the integrity of a software system.&#160; With such specifications, the development team has an objective measure by which to weigh the software behavior against prior to it being delivered to a customer … thus equipping the development team with the ability to always produce bug-free software.</p>  <p>&#160;</p>  <hr />  <p>1. &#8216;Agile&#8217; Development Winning Over &#8216;Waterfall&#8217; Method &#8211; <a href="http://itmanagement.earthweb.com/entdev/article.php/3841636/Agile-Development-Winning-Over-Waterfall-Method.htm">http://itmanagement.earthweb.com/entdev/article.php/3841636/Agile-Development-Winning-Over-Waterfall-Method.htm</a></p><img src="http://feeds.feedburner.com/~r/AspiringCraftsman/~4/FZSHILYkyDI" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://aspiringcraftsman.com/2011/10/18/how-to-produce-bug-free-software/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		<feedburner:origLink>http://aspiringcraftsman.com/2011/10/18/how-to-produce-bug-free-software/</feedburner:origLink></item>
		<item>
		<title>Dependency Management in .Net: install2</title>
		<link>http://feedproxy.google.com/~r/AspiringCraftsman/~3/nfBfKeNdJBo/</link>
		<comments>http://aspiringcraftsman.com/2011/09/27/dependency-management-in-net-install2/#comments</comments>
		<pubDate>Tue, 27 Sep 2011 01:42:20 +0000</pubDate>
		<dc:creator>derekgreer</dc:creator>
				<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://www.aspiringcraftsman.com/?p=766</guid>
		<description><![CDATA[Inspired by Rob Reynolds’ awesome post on extending NuGet’s command line, I decided to create my own extension for facilitating application-level, build-time retrieval of external dependencies along with all transitive dependencies. I struggled a bit with what to call the command since what it does is really what I believe the regular install command should [...]]]></description>
			<content:encoded><![CDATA[<p>Inspired by <a href="http://twitter.com/#!/ferventcoder">Rob Reynolds</a>’ <a href="http://geekswithblogs.net/robz/archive/2011/07/15/extend-nuget-command-line.aspx">awesome post</a> on extending NuGet’s command line, I decided to create my own extension for facilitating application-level, build-time retrieval of external dependencies along with all transitive dependencies.  I struggled a bit with what to call the command since what it does is really what I believe the regular install command should be doing (i.e. installing transitive dependencies), so I decided to just call it install2.  Here’s how to use it:</p>

<blockquote>

<p><strong>Step 1</strong>: Install the NuGet Extension package by running the following command:</p>
<pre class="brush:shell; gutter:false; wrap-lines:true;">
$&gt; NuGet.exe Install /ExcludeVersion /OutputDir %LocalAppData%\NuGet\Commands AddConsoleExtension
</pre><br />
<p><strong>Step 2</strong>: Install the extension by running the following command:</p>
<pre class="brush:shell; gutter:false; wrap-lines:false;">
$&gt; NuGet.exe addExtension nuget.install2.extension
</pre>
<br />
<p><strong>Step 3</strong>: Create a plain-text packages file (e.g. dependencies.config) listing out all the dependencies you need.  For example:</p>
<pre class="brush:shell; gutter:false; wrap-lines:false;">
NHibernate 3.2.0.4000
Moq
</pre><br />
<p><strong>Step 4</strong>: Execute Nuget with the install2 extension command:</p>
<pre class="brush:shell; gutter:false; wrap-lines:false;">
$&gt; NuGet.exe install2 dependencies.config
</pre></blockquote>
<br />
<p>If all goes well, you should see the following output:</p>

<pre class="brush:shell; gutter:false; wrap-lines:false;">
Attempting to resolve dependency 'Iesi.Collections (3.2.0.4000)'.
Successfully installed 'Iesi.Collections 3.2.0.4000'.
Successfully installed 'NHibernate 3.2.0.4000'.
Successfully installed 'Moq 4.0.10827'.
</pre>


<p>Enjoy!</p><img src="http://feeds.feedburner.com/~r/AspiringCraftsman/~4/nfBfKeNdJBo" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://aspiringcraftsman.com/2011/09/27/dependency-management-in-net-install2/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		<feedburner:origLink>http://aspiringcraftsman.com/2011/09/27/dependency-management-in-net-install2/</feedburner:origLink></item>
	</channel>
</rss><!-- Dynamic page generated in 0.896 seconds. --><!-- Cached page generated by WP-Super-Cache on 2012-02-05 12:21:05 -->

