I have been writing javascript for some time now and recently have been spending some time with Node.js. The javascript as a first class language movement is still very young and we are finding new things about javascript every day. Most of them are good; some of them aren't so good.

I have been making note of patterns that I've come across, developed or read throughout the javascript world. These patterns are in the style of good javascript practice as well as pattern languages that will allow javascript developers to communicate implicitly with other developers. If you are curious about more of these patterns, I suggest reading the Gang of Four Design Patterns book and then moving on to Martin Fowler's work and writings.

Immutable Object Pattern

Alternative names new object pattern
Description The immutable object pattern prevents us to making changes to external objects within a function. Often this means creating a new object and returning it rather than modifying parameters.
Reasoning Javascript is a functional-enabled language. Functions are treated as first class citizens in the language. However, the functional quality is not enforced. The immutable object pattern defines a practice that allows us to treat javascript as a functional language. This means that we can apply functions across objects without worrying about the object changing (and we can grab the new changed object from the return of those functions).

If you're writing javascript in a functional way, you will want to use good functional practices. Most functional languages will enforce immutability (to a degree). In Haskell, everything but monads are immutable. In scheme, you need to use special mutation functions like set!. In Javascript, this is not enforced.

The biggest offenders in the javascript community that I've seen is the code that I've read that was written for Node.js. For example, the following is a (sanitized) version of a popular Node.js project.

    function proxy(request, response) {
        request.headers.host = "api.com";
        request.url = "/api/" + request.url.match(/^\/myAPI\/(.*)$/)[1];
        delete request.headers.cookie;

        var proxy = HTTP.createClient(80, request.headers.host);
        var proxy_request = proxy.request(request.method, request.url, request.headers);

        request.addListener("data", function(chunk) {
            proxy_request.write(chunk);
        });
        request.addListener("end", function() {
            proxy_request.end();
        });

        proxy_request.addListener("response", function (proxy_response) {
            proxy_response.addListener("data", function(chunk) {
                response.write(chunk);
            });
            proxy_response.addListener("end", function() {
                response.end();
            });
            response.writeHead(proxy_response.statusCode, proxy_response.headers);
        });
    }

The above code takes a request and reroutes it to an external API. It works great and the project is small enough that someone could very easily understand what is going on. However, let us imagine that it was a slightly larger project with about 1,000 - 2,000 lines of code. The code that uses the proxy in the hypothetical project looks something like this:

    function handleRequest(request, response) {
        if (request.url.match(/^\/myAPI\/(.*)$/))
            proxy(request, response);
        else
            getDataFromDatabase(request, response);
    }

And now we want to store the myAPI requests in our own database for logging purposes. In a functional, immutable language we would write something like this:

    function handleRequest(request, response) {
        if (request.url.match(/^\/myAPI\/(.*)$/)) {
            proxy(request, response);
            log(request);
        } else
            getDataFromDatabase(request, response);
    }

However, this doesn't work the way that we would expect it. After we run the proxy function, the request object has been modified and is now a request to the external API. We could resolve this by storing a local variable or calling the log function first (assuming the log function is immutable!). Add another mutable function into the mix, though, and the local variable becomes the only solution.

the rock of gibralter

When using the immutable object pattern, do not change the object! We can look and read the object, but we don't know and cannot change the internals of the object we are accessing.

Photo by kathrynvjones. Distributed under CC-by-nc-sa.

In order to make the proxy function operate as expected, we need to make it follow the immutable object pattern. This means that we aren't modifying the request object that is passed in. [1]

    function proxy(request, response) {
        var proxy = HTTP.createClient(80, "api.com");
        var proxy_request = proxy.request(request.method, "/api/"
            + request.url.match(/^\/myAPI\/(.*)$/)[1],
            {'post':request.headers.post});

        // below here is the same as before
    }

You can see in the modified code above that we are merely reading the information off of the request object and never modifying the request object itself. This allows us to use the request object in the handleRequest function without having to worry about the object changing from under us.

This pattern is a good practice but should not always be used. Even in 'pure' functional languages such as Haskell and Scheme, there are circumstances where mutability is required. However, the more immutable our programs and libraries are, the safer they become to use. When it makes sense, we should use this pattern where ever possible.

Module as object-oriented package

Alternative names OO-Module
Description The OO-Module is similar to the packages of an object oriented language such as Java and C#. The modules only contain class definitions.
Reasoning Javascript being a prototypical language and Modules 1.1 of CommonJS both give the developer a wide range of options when organizing a package. OO-Module and Function Module (seen next) both give us a structured, predictable way of organizing our javascript modules.

Coming from an object oriented background, my first instinct on a big javascript project was to create classes and objects. However, as my projects grew I realized that dealing with a bunch of different classes at the same 'package' level was a hassle. Folders weren't a great option by themselves. So, I started writing modules something along the lines of this

    // A top-level module with the following folder structure
    //    myModule.js
    //    myModule/
    //    - myModule.js
    //    - another.js
    //    - last.js
    //    - somePrivateInternalClass.js
    exports.myModule = require("./myModule/myModule").myModule;
    exports.another = require("./myModule/another").another;
    exports.last = require("./myModule/last").last;

Where the actual code only exists inside of the folder. This allows us to control the exposure, by convention, of classes. For example, somePrivateInternalClass is never 'exposed' to the outside world (though nothing is stopping us from requiring it). This also means that we know exactly how to access a public class through any package. It is just require("path/to/package").PublicClass.

It should be noted that we should never be using the exports object to transport an entire class. For example, the following code is an anti-pattern

    var AntiPattern = function() {

    };

    AntiPattern.prototype.doSomething = function() {};

    exports = AntiPattern;

While currently safe in most instances on both Narwhal and Node.js, there is no promise that the exports object will not change in the future. Instead, you should export classes as properties on the exports object.

sky patterned with trees

Photo by dramaqueennorma. Distributed under CC-by-nc-sa.

Module as a function library

Alternative names Function-Module
Description The function module is a collection of functions that are not tied to a particular object. This is the pattern that you'll most likely use for mix ins (see below) or utility modules.
Reasoning Javascript being a prototypical language and Modules 1.1 of CommonJS both give the developer a wide range of options when organizing a package. OO-Module (seen previous) and Function Module both give us a structured, predictable way of organizing our javascript modules.
    exports.functionA = function() {};
    exports.functionB = function(arg) {};
    exports.functionC = function(arg, arg2) {};

And using it looks something like this

    require("myModule").functionA();
    require("myModule").functionB(1);
    require("myModule").functionC(1, 2);

While this is a simple pattern, I have gotten myself into trouble by mixing the two styles of modules in one module. Each of your modules should either by a Function module or an OO module. Function modules can be extended and organized in a way similar to the OO module by using mix ins. [2]

Mix Ins

Alternative names Runtime Import, Extensions
Description Mix ins allow us to extend a class or function module without bloat. It also, in some circumstances, allow us to re-use certain functions that are common among unrelated segments of code.
Reasoning Having large, complex files makes working with code difficult. For that reason, many languages and IDEs have ways of managing packages and files. In javascript, we have nearly limitless methods of organizing our code and run time extensions are another way to manage our code.

A while back, I wrote a blog post about mix ins. Since then I have had a bit more experience with javascript and there are actually two different styles of mix ins. There is the OO mixin and the function mixin. First, the mix in class will always by a function module (see above). It may look something like this:

    exports.functionA = function() {};
    exports.functionB = function(arg) {};
    exports.functionC = function(arg, arg2) {};

In an OO mix in, we mix these functions in inside of the constructor.

    ...

    var MyClass = function() {
        for(var x in require("mixin"))
            this[x] = require("mixin")[x];
    }

    ...

In a function mix in, we mix these functions in to the exports object.

    ...

    for(var x in require("mixin"))
        exports[x] = require("mixin")[x];

    ...

The function mix ins are a great way to organize a big function module. We can use the function mixin to include a whole set of subfiles that allow logical grouping of these files for easier navigation.

sand patterns

Photo by Geograph.org.uk. Distributed under CC-by-sa.

    // A top-level module with the following folder structure
    //    myModule.js
    //    myModule/
    //    - myModule.js
    //    - another.js
    //    - last.js
    //    - somePrivateInternalClass.js
    for(var x in require("./myModule/myModule"))
        exports[x] = require("./myModule/myModule")[x];

    for(var x in require("./myModule/another"))
        exports[x] = require("./myModule/another")[x];

    for(var x in require("./myModule/last"))
        exports[x] = require("./myModule/last")[x];

Which, like the OO module, allows us to 'hide' certain functions from the public by convention.

Class Method

Alternative names Creator method, Factory method
Description The class method is a version of a factory method that exists and operates similar to that of an OO class method. These methods are usually for constructing and returning underlying objects.
Reasoning Creating objects can be a hassle. We have to construct the object, set up the dependencies and set up the data. This can also create duplicate code all over our code base. In order to reduce this, we want to create a method close to the class that will construct a particular object for us.

Class methods are nothing new and are often factory methods. In javascript, though, there is no real concept of a "class method". We get around this by creating a function right next to the definition of the class.

    ...

    var MyClass = function() {

    };

    var createMyClass = function(someData) {
        var result = new MyClass();
        result.someData = someData;
        return result;
    };

    ...

This pattern is the one that I see most often in libraries and I love the fact that they use this. I don't want to have to know the internals of an HTTP request in order to use it; I just need to create the request. Creator methods make this a breeze and keep developers writing interesting code rather than reading through code they don't need to know about for their particular solution.

[1] I'm making a guess that they want the POST headers here. I'm not sure what else they may want from the headers. [2] There is an exception to this. 'Class methods' are acceptable to be used within an OO module.