Either.js

Some time ago, I was watching this excellent video course by Neal Ford titled “Functional Thinking – Functional Programming using Java, Clojure and Scala”. In one of the modules on functional data structures, Neal talks about this container type in Scala named Either.

The Either type in Scala represents one of two possible values, a Left value or a Right value.  The convention dictates that the Left value is used for error or exception objects, while the Right value is used for normal values. Why is this useful?

In many programming languages, like Java, C#, JavaScript, Scale, etc. …, there are generally two ways a function or method call returns something. The first one is through a regular return value that is returned by a function/method, be it some primitive type or some object. The second one is by throwing an exception, which means that the return value of the  function/method in question is not available to the calling code. In order to deal with this dual behavior, the calling code has to verify/use the value returned when invoking a function or method as well as dealing with possible exceptions  that this function/method might throw.

This is where the Either type comes in, unifying both behaviors by offering a Left value containing a possible error/exception object or a Right value containing the regular output of a function/method. In his course, Neal further elaborates on this concept by implementing a similar Either type in Java using interfaces because Java has no support for lambda’s yet (ouch).

While working on some JavaScript code a while back, I ran into this situation where the code in question could really benefit by using the concept of an Either object. So I decided to implement such an object in JavaScript and extracted the result into a Node.js module named either.js that I recently published on npm.

Take a look at the following code sample:

_this.insertReport = function(dataArea, inventoryReport, callback) {
    simulateAsynchronousIO(function() {
        var reportsCollection = _dataAreas[dataArea];
        if(!reportsCollection) {
            var error = new InvalidDataAreaError('The specified area is unknown.');
            callback(error);
            return;
        }

        reportsCollection.push(inventoryReport);
        callback();
    });
};

 

There were a couple of functions like this one where an array was being retrieved from an object named _dataAreas which contains a number of array properties. In case the specified property name could not be found on the containing object, the callback was invoked with an error object. Using an Either object, this code got revamped into something like this:

 

_this.insertReport = function(dataArea, inventoryReport, callback) {
    simulateAsynchronousIO(function() {
        getReportsCollectionFor(dataArea).fold(
            function left(error) { 
                callback(error); 
            },
            function right(reportsCollection) {
                reportsCollection.push(inventoryReport);
                callback();        
            }
        );
    });
};

function getReportsCollectionFor(dataArea) {
    reportsCollection = _dataAreas[dataArea];

    if(reportsCollection)
        return either.right(reportsCollection);
    else
        return either.left(new InvalidDataAreaError('The specified area is unknown.'));
}

 

I admit that there’s definitely some getting used to at first, but I find this approach to be very clean and useful. In fact, this kind of reminds me to the beauty of using promises for asynchronous code, but for synchronous code instead.

Until next time.

Basic JavaScript: Prototypical Inheritance vs. Functional Inheritance

Inheritance in JavaScript has been the topic of many discussions in the past and will continue to be the source of future debates and arguments. While we do value composition over inheritance, we don’t want to throw the baby out with the bathwater either. So, from time to time, we run into these cases where we want some notion of inheritance in JavaScript. Now what?

As with many things in JavaScript, there is not a single straight answer. We can choose between a couple of options and many different variations of these solutions. But one thing’s for sure: we can’t have it all!

In this blog post I want to discuss two different styles of inheritance that I have a hard time choosing from when programming JavaScript. And as with everything in life, both styles have their own pros and cons. 

Prototypical inheritance

In ‘classical’ programming languages, one class can directly inherit from another class. JavaScript doesn’t have this notion of classes (yet). Instead, JavaScript has prototypes which you can augment to fit your own needs. This means that having a single augmented object as the prototype for other objects, which ‘inherit’ all members of the augmented prototype object, kind of simulates a pseudo-classical inheritance pattern. Let’s talk code in order to demystify this concept.

// validator.js
var Validator = exports.Validator = function() {
    this._rules = [];
};

Validator.prototype.addRule = function(rule) {
    this._rules.push(rule)
};

Validator.prototype.validate = function(instance) {
    ...
};

// specificValidator.js
var util = require('util');

var SpecificValidator = function() {
    Validator.call(this);
};

util.inherits(SpecificValidator, Validator);

SpecificValidator.prototype.filter = function(instance) {
    ...
};

// client.js
var validator = new SpecificValidator();

// Calls function on derived object
validator.filter( { ... } );        

// Calls function on base object
validator.validate( { ... } );        

Here we have a constructor function named Validator which is the base object for other ‘derived’ objects. We augment the prototype with two functions (addRule and validate). Next we define another constructor function named SpecificValidator. We ‘derive’ this new  constructor function by calling the base constructor function and wiring the prototype by using the util.inherits() function from the Node.js core library.

We have to use the new keyword in order to instantiate a SpecificValidator object. Now we can use the functions that we added to the prototype.

Functional inheritance

This pattern is advocated by Douglas Crockford in his book JavaScript, The Good Parts. There he offers this particular style as the way to go for inheriting objects. Let’s look at an example.

// validator.js
module.exports = function() {
    var rules = [], my = {};

    my.addRule = function(rule) {
        rules.push(rule);
    };

    my.validate = function(instance) {
        ...
    };

    return my;
};

// specificValidator.js
var validator = require('...').validator;

var specificValidator = function() {
    var my = validator();

    my.filter = function(instance) {
        ...
    };
    
    return my;
};

// client.js
var validator = specificValidator();

// Calls function on derived object
validator.filter( { ... } );    

// Calls function on base object
validator.validate( { ... } );        

The base constructor function returns an object that is augmented with functions and is returned at the end. The derived constructor function simple calls the base constructor function and further augments the retrieved object before returning it to the calling code. Here we don’t have to use the new keyword to instantiate anything. Just calling the right constructor function gives us an object which we can use in our client code.

Conclusion

The most important benefit of prototypical inheritance, at least in my humble opinion, is performance. By augmenting the prototype with functions, we only create these functions once. Not matter how many times we instantiate a constructor function, the same functions get (re)used every single time. Functional inheritance on the other hand creates new functions every time a constructor function is called, which is several orders of magnitude slower compared to the prototypical inheritance pattern.

On the other hand, the prototypical approach doesn’t come with encapsulation. Looking at the example shown earlier, the ‘_rules’ property is publicly available to the client code and can be manipulated at will. By using a simple convention, like prefixing with an underscore, we can indicate that these private members should not be touched in order to guarantee a correct behavior. But again, nothing can be enforced. Using functional constructors, we can have private variables and functions that cannot be manipulated by the calling code.    

There are more pros and cons, but for me, these are the most important ones to be aware of. You can see that both styles have their strengths and weaknesses. I usually tend to go with prototypical inheritance as this is the ‘JavaScript way’, but I like using the functional approach as well for those cases were I know in advance that not too many objects are created or when I don’t care about performance.

I would love to hear other takes on this. What particular styles do you use? When do you use them and why?

Until next time

Writing Fast, Memory-Efficient JavaScript

Earlier this week, I read this great article titled “Writing Fast, Memory-Efficient JavaScript” by Addy Osmani. This is a highly recommended read for anyone involved in writing JavaScript code.

The topics that I found to be particularly interesting were the apparent fact that it’s better to avoid the delete keyword and cached functions in the module pattern. The major down-side that I see when using cached functions is that you can’t have any private variables within your module. But this is highly interesting stuff, nonetheless.

Taming that client-side javascript mess with Backbone.js–Boise Code Camp session materials

I had a blast presenting on Backbone.js at Boise Code Camp this weekend. Thanks to all who attended! I received a lot of positive feedback and as such will be presenting the same talk at the Boise Web Technologies Group Thursday, April 26, 2012, 6:00 PM. RSVP here

Slides & Source http://bit.ly/bcc12_backbonejs
Blog post Resources for getting started with Backbone.js

 

(If you are interested in my presenter notes you can find the original powerpoint in the link above)

Resources for getting started with Backbone.js

The current product I am building makes heavy use of HTML5 & javascript to give the user a rich experience, both on and offline, across a variety of screens. Before I even started this application I knew I wanted a clean and proven approach to help manage the complexity on the client. After reviewing several js frameworks I decided to go with backbone.js (compare yourself). I have been working with backbone for several months and I am really happy with it, and would recommend to anyone building similar types of javascript applications.

As per the project description:

Backbone supplies structure to JavaScript-heavy applications by providing models with key-value binding and custom events, collections with a rich API of enumerable functions, views with declarative event handling, and connects it all to your existing application over a RESTful JSON interface.”

There are a ton of good ‘getting started’ posts out there, so rather than duplicate those I thought I would put together a few of my favorite resources. Hopefully some of you might find them useful.

  • Backbone.js : The main github site- Here you will find valuable reference documentation as well a simple examples to introduce you to backbone. Be prepared to spend a little time here 😉
  • Underscore.js : “It’s the tie to go along with jQuery‘s tux, and Backbone.js‘s suspenders.”  If you haven’t heard about underscore do yourself a favor on go check it out. There is nothing magical about it, yet I can’t say enough. Even if you aren’t using backbone, I highly recommend this library (some folks are using it on the server with node.js as well).
  • Todo.js : A simple Todo list example using backbone.js
  • TodoMVC : Compare a truck load of JS MVC frameworks – “a project which offers the same Todo application implemented using MVC concepts in most of the popular JavaScript MVC frameworks of today.”
  • Backbone.js Fundamentals : A book on Backbone.js targeted at beginners and advanced users alike – by Addy Osmani (and contributors). This guide is quickly becoming the ‘mini-bible’ for backbone. Chalked full of nuggets, from beginning concepts to the more advanced.
  • The Backbone Boilerplate : “Backbone Boilerplate is a set of best practices and utilities for building Backbone.js applications”
  • Organizing Your Backbone.js Application With Modules : Some guidance around how you might structure your application using modules (esp valuable for larger applications).
  • Organizing your application using Modules (require.js) : Similar to the previous article, but makes use of AMD & Require.js to wire up the application.
  • Derick Baileys blog on Lostechies : Derick has been blogging on backbone for 6 mos or so. I appreciate reading Dericks blog because he has done such a good job of cataloging his experiences as he has learned the framework. When I found myself stumbling with backbone, my searches often led over to Dericks blog.
  • Backbone.js Screencast – Introduction and Views : A nice “basic introduction on how to bootstrap a new Backbone.js application and go in-depth on how to use Backbone Views in particular”. Joey now also has screencasts available over at his site http://backbonescreencasts.com/
  • Backbone.js walkthrough of Models and Views (Part 1/2) Screencast : Enough said!
  • Using node.js + backbone.js + socket.io for real-time goodness : I haven’t actually implemented this yet, but am excited about the possibilities. Check out here here and here for some examples. (seeing how the middle tier in this app is MVC.net, I may opt to swap socket.io for signalR. Hoping to take the node.js plunge at some point).

Updated:

That’s all for now. Please feel free to reach out with any other resources you found helpful and Ill add them on here. I am still very much learning and would love to read your posts. More to come-

Basic JavaScript Part 12: Function Hoisting

Here are the links to the previous installments:

  1. Functions
  2. Objects
  3. Prototypes
  4. Enforcing New on Constructor Functions
  5. Hoisting
  6. Automatic Semicolon Insertion
  7. Static Properties and Methods
  8. Namespaces
  9. Reusing Methods of Other Objects
  10.   The Module Pattern
  11.   Functional Initialization

In a previous post I already discussed the phenomenon of hoisting in JavaScript. In that post I showed the effects of variable hoisting and why it’s important to declare all variables at the top of a function body. For this post I want to briefly focus on function hoisting. Let’s start off with an example to illustrate this concept.

functionExpression();        // undefined
functionDeclaration();        // "Function declaration called."        

var functionExpression = function() {
    console.log('Function expression called.');
};

functionExpression();        // "Function expression called."
functionDeclaration();        // "Function declaration called."

function functionDeclaration() {
    console.log('Function declaration called.');
}

functionExpression();        // "Function expression called."
functionDeclaration();        // "Function declaration called."

In order to understand what’s going on here, we first need to understand the distinction between a function expression and a function declaration. As it’s name implies, a function expression defines a function as part of an expression (in this case assigning it to a variable). These kind of functions can either be anonymous or they can have a name.

// 
// Anonymous function expression
//
var functionExpression = function() {
    console.log('Function expression called.');
};

// 
// Named function expression
//
var functionExpression = function myFunctionExpression() {
    console.log('Function expression called.');
};

On the other hand, a function declaration is always defined as a named function without being part of any expression.

So, for the example shown earlier, the function expression can only be called after it has been defined while the function declaration can be executed both before and after it’s definition. Let’s look at how JavaScript actually interprets this code in order to explain why it behaves that way.

var functionExpression,        // undefined
    functionDeclaration =  function() {
        console.log('Function declaration called.');
     };
     
functionExpression();        // Still undefined
functionDeclaration();        // "Function declaration called."        

// The assignment expression is still left at the original location
// although the variable declaration has been moved to the top. 
functionExpression = function() {
    console.log('Function expression called.');
};

functionExpression();        // "Function expression called."
functionDeclaration();        // "Function declaration called."

// Here we originally defined our function declaration
// which has been completely moved to the top.

functionExpression();        // "Function expression called."
functionDeclaration();        // "Function declaration called."

JavaScript turns our function declaration into a function expression and hoists it to the top. Here we see the same thing happening to our function expression as I explained in the previous post on variable hoisting. This also explains why the first call of our function expression results in an error being thrown because the variable is undefined.  

So basically, JavaScript applies different rules when it comes to function hoisting depending on whether you have a function expression or a function declaration. A function declaration is fully hoisted while a function expression follows the same rules as variable hoisting. It definitely took me a while to wrap my head around this.

Until next time.

Basic JavaScript Part 11: Functional Initialization

Here are the links to the previous installments:

  1. Functions
  2. Objects
  3. Prototypes
  4. Enforcing New on Constructor Functions
  5. Hoisting
  6. Automatic Semicolon Insertion
  7. Static Properties and Methods
  8. Namespaces
  9. Reusing Methods of Other Objects
  10.  The Module Pattern

I just want to quickly share some beautiful JavaScript code I picked up while watching the most excellent screencast 11 More Things I Learned from the jQuery Source by Paul Irish.

var base = dom.getElementByTagName('base')[0] | | (function() {
     // Do some stuff
     return someElement.insertBefore(dom.createElement('base'), someElement.firstChild) ;
})(); 

This single line of code basically checks whether there’s a base tag somewhere in the DOM. If there is one, then it assigns the reference for the first element to the base variable. If it’s not in the there, then a self-executing function inserts a new base tag into the DOM and returns the reference to the new element.

I don’t know about you, but I think this is pretty neat.

Basic JavaScript Part 10: The Module Pattern

Here are the links to the previous installments:

  1. Functions
  2. Objects
  3. Prototypes
  4. Enforcing New on Constructor Functions
  5. Hoisting
  6. Automatic Semicolon Insertion
  7. Static Properties and Methods
  8. Namespaces
  9. Reusing Methods of Other Objects
    The module pattern is quite popular in the JavaScript community as is heavily applied by many JavaScript developers. There’s also the CommonJS initiative, which defines a specification for a common set of JavaScript API’s that are organized using self-contained modules. These specifications are supported by a growing community as they provide the foundation for the modules that are built into Node.js and numerous other open-source JavaScript libraries. This pattern has become so widespread because it’s an excellent way to package and organize an independent, self-containing piece of JavaScript code. The module pattern is composed by using self-executing functions combined with namespaces. Let’s show a simple example.

    namespace('media');
    
    media.podcast = (function(name) {
        var fileExtension = 'mp3';        
    
        function determineFileExtension() {
            console.log('File extension is of type ' + fileExtension);
        }
        
        return {
            download: function(episode) {
                console.log('Downloading ' + episode + ' of ' + name);
                determineFileExtension();
            }
        }    
    }('Astronomy podcast'));

    First we define a namespace called media. Then we use a self-executing function that returns an anonymous object with a method named download that can be invoked by external code. Inside the self-executing function we have a variable fileExtension and a function determineFileExtension that are private and can only be used inside the module. Notice that we provide a fixed parameter value for the self-executing function. This technique is usually applied to pass in some kind of global object. jQuery uses this same approach to inject a reference to the global window object into the scope of its module.

    We can use the download method of our module like so …

    media.podcast.download('the first episode');

    … which outputs what we expect:

    Downloading the first episode of Astronomy podcast

    File extension is of type mp3

    The way we implemented the module pattern here has at least one major downside. We’re able to completely replace the implementation of the download method that is exported by the anonymous object returned from the self-executing function. This can become quite troublesome if we have other functions inside our module that also make use of the download method and thereby rely on its functionality. The way to fix this issue is to make all functions private and export them using the anonymous object:

    namespace('media');
    
    media.podcast = (function(name) {
        var fileExtension = 'mp3';        
    
        function determineFileExtension() {
            console.log('File extension is of type ' +fileExtension);
        }
        
        function download(episode) {
            console.log('Downloading ' + episode + ' of ' + name);
            determineFileExtension();
        }
        
        return {
            download: download
        }    
    }('Astronomy podcast'));
    The download method exposed by the anonymous object can still be replaced, but at least the correct implementation is preserved by the private download function for other functions that rely on its behavior. This approach is commonly called the “revealing module pattern”
    Another neat approach is to export a constructor function instead of an anonymous object.
    namespace('media');
    
    media.Podcast = (function() {
        var fileExtension = 'mp3';        
    
        function determineFileExtension() {
            console.log('File extension is of type ' +fileExtension);
        }
        
        var podcastConstructor = function Podcast(name) {
            if(false === (this instanceof Podcast)) {
                return new Podcast();
            }
            
            this.getName = function() {
                return name;
            }
        }
        
        podcastConstructor.prototype.download = function (episode) {
            console.log('Downloading ' + episode + ' of ' + this.getName());
            determineFileExtension();
        }
        
        return podcastConstructor;
    }());
    Instead of returning an anonymous object from our self-executing function, we create another function and add the download method to the prototype of this constructor function. Notice that we also moved the name parameter to the constructor function instead of passing it into the self-executing function. At the end of the self-executing function we just return this constructor function like we did with the anonymous object.
    We can now use this module like so …
    var astronomyCast = new media.Podcast('Astronomy podcast');
    astronomyCast.download('the first episode');
    … which yields the same output as before.
    The module pattern is a very powerful concept in JavaScript. Being able to expose and use JavaScript code, treating it as a black box, is a very common technique that is used in lots of JavaScript libraries and frameworks.

Happy coding!