Category: code

Javascript Module Pattern: A Detailed Deconstruction

The term module is a convention used in Javascript to group code that’s conceptually coherent. The Module Pattern is a programming design pattern that uses modules as the basic construct for organizing code.

Javascript Module Pattern by omarrr

Wikipedia defines Modular Programming as follows

[…] a software design technique that emphasizes separating the functionality of a program into independent, interchangeable modules, such that each contains everything necessary to execute only one aspect of the desired functionality.

The basic module

The absolute most basic Javascript module is actually a Javascript object

var Module = {
    foo: 'hello world'
}

By itself this doesn’t seem like a very useful pattern but just by grouping under this object all variables needed we can get a great replacement for global variables

var Module = {
    foo: 'hello world',
    bar: 12345,
    baz: ["John", "Joe", "Josh"],
    qux: {x: 100, y: 300}
}

The Object-Module Pattern

Javascript object keys can hold functions also, which means that this simple module is a quick way to package our code consisting of both variables and functions.

var Module = {
    foo: 1,

    bar: function() {
        console.log(foo); // ReferenceError: foo is not defined
        console.log(this.foo); // 1
        console.log(Module.foo); //1
    }
};

Public access

Variables defined as in the example above are public and can be access directly

Module.foo = 3;
Module.bar();

Within the module’s bar the value of this equals Module, which means that the following two lines are equivalent when used inside bar

console.log(this.foo);
console.log(Module.foo);

Trying to access foo without the this qualifier or the namespace Module will throw a Reference error since there is no foo global variable defined.

Dynamic content

Modules allow for new variables to be added on the fly. This code is ok even if we’ve never declared the qux member before.

Module.qux = 2;

This simple module pattern is more a Javascript code grouping technique. It is the most basic example of Javascript namespacing and a good replacement for using any global variable. You should always be able to replace all your global variables and functions for this code:

var MyNamespace = {};

MyNamespace.qux = "my new namespaced var (aka global)"

Full Example

Here’s a complete example of this Module Type:

var Module = {
    foo: 1,

    bar: function() {
        console.log(this); // ok! (=Module)
        console.log(++this.foo); // ok!
        console.log(++Module.foo); // ok!
    }
};

// Public access
console.log(++Module.foo); // ok!
Module.bar();

// Allows for new variables to be added on the fly
Module.qux = 2;

The Functional-Module Pattern

The Functional-Module Pattern is very similar to the Object-Module described above, but instead of creating an object directly through the object notation, we create it as a result of executing a function.

Compare

var Module1 = {
    foo: 10,
    bar: function(){ alert("hi");}
}

with

var Module2 = (function(){
    return { 
        foo: 10,
        bar: function(){ alert("hi");}
    };
}());

both Module1 and Module2 define an identical object, but utilizing the second syntax we can take advantage of closures.

The Closure-Module Pattern

A Closure is a function, plus the environment (or scope) it was declared in. Only functions, created inside functions are closures, and they can make our objects a tad more powerful and a lot more secure by:

  • Data encapsulation: providing private member fields and methods
  • Persistence of local scope: allowing public and private methods access to a private scope unique to the Module at hand

Implementing Private Members

In the example below the variable _foo can be considered as a private member:

var Module = (function(){
    var _foo = 20;
    return { 
        bar: function(){ alert("hi");}
    };
}());

_foo is inaccessible to external code and so this code will return ‘undefined’

console.log(Module._foo); // undefined

(By the way, naming private variables starting with _ is a good common practice to easily differentiate between public and private variables and functions).

Taking advantage of the local scope

bar in the example above, however, is truly private and could be used with in the public (and private) functions declared inside Module. See the example below:

var Module = (function(){
    var _foo = 20;
    return { 
        bar: function(){ console.log(_foo);}
    };
}());

Calling the public method bar of Module will output the value of _foo, however trying to access the value directly from outside of Module will now work

Module.bar(); // 20
console.log(Module._foo); // undefined

We have effectively created a private variable that’s inaccessible to code outside of Module that can be used by internal functions for keeping the local state.

Closures are great when writing APIs and code to be used by other developers while keeping the integrity of the API itself.

Dynamic Members

The Module Pattern permits us to have, not only public and private members, but also dynamic variables and functions. Since the returned Module is a regular Javascript object we can extend it as we would normally do in Javascript

Module.qux = 20;
Module.qux = function(){ console.log(this.qux); };

The —so called— Constructor

So up until now I’ve used this format of the Module pattern:

var Module = (function(){
    var _foo = 0;

    return {
        bar: 1,
    }
}());

I personally find that using a more explicit format makes it more clear to read and understand. Here:

var Module = (function(){
    var _foo = 0;

    var self = {
        bar: 1,
    }

    return self;
}());

In this case it is clear that the value of Module is the object selfreturned by the function. This is informally called the constructor of the Module.

Even better, this exact same thing can be expressed as:

var Module = (function(){
    var _foo = 0;

    var self = {};

    self.bar = 1;

    return self;
}());

I like this last representation best since it consists mostly of regular Javascript functional expressions (vs. object notation).

Self-referencing

Using this —so called— constructor syntax gives us a way to reference the module itself from within the module’s private member functions. Without a variable self a private method would have no means to call a public variable or function.

Self-referencing varies depending on the scope of the caller and the callee. What this means is that in order to call a function of a module we must understand the scope of the function that’s calling and the function that’s being called, since there are rules for each.

Private access within a Module

Accessing private members can be done directly without any qualifier from private or public functions. Dynamic functions can’t access private members.

var Module = (function(){
    var _foo = 10;
    var _bar = function (){ console.log(_foo)};

    var self = {
        baz: function (){ console.log(_foo)};
    }

    return self;
}());

Public access within Module

Accessing public members from within private or public functions can be done using the self variable. Additionally public functions can also access public members via ‘this’ keyword.

var Module = (function(){
    var _foo = function (){ console.log(self.bar)};

    var self = {
        bar: 1,
        baz: function (){ console.log(self.bar)}; // this works
        qux: function (){ console.log(this.bar)}; // this works too
    }

    return self;
}());

Access from within dynamic members

Dynamic functions must always use the keyword this to access public and other dynamic members. This is one of the awesome things about Javascript closures. Since the dynamic functions were not in the same scope as the Module itself when created, they don’t have access to private methods (not even self). That means that developers can’t use dynamic members to get around the private scope limitations.

var Module = (function(){
    var _foo = 10;

    var self = {
        bar: 20,
    }

    return self;
}());

Module.qux = (function(){ 
    console.log(this._foo); // undefined
    console.log(this.bar); // 20
});

Summary

There are several ways to express the Module patter and all of them are equivalent. In any case taking advantage of closures will make modules that much more powerful.

Closure-based Pattern

This is the minimum expression of the Module Pattern. I personally like this syntax best, since I believe it offers best readability:

var m = (function(){
    var _foo = "I'm private";

    var self = {};

    self.bar = "I'm public";

    return self;
}());

A complete example: All put together

Here’s a complete example that shows public and private variables and functions.

var Module = (function(){
    // private variables
    var _v1 = 10;

    // private methods
    var _f1 = function(){ 
        console.log(_v1);
        console.log(self.v2);
        console.log(self.v3);
    };

    // constructor
    var self = {};

    // public variables
    self.v2 = 20;

    // public functions
    self.f2 = function(){
        console.log(_v1);
        console.log(self.v2);
        console.log(self.v3);
    };

    return self;
}());

// Dynamic Members
Module.v3 = 30;
Module.f3 = function(){ 
    console.log(this.v2); 
    console.log(this.v3); 
};

// Usage
console.log(Module.v2);
Module.f2();
console.log(Module.v3);
Module.f3();

References

5 Easy Steps to Archive a Github Repo on Bitbucket

So I love Github. I use it for personal projects and for work. I’m happy to pay for the service but I find myself constantly running out of space because of old private repos. Most of the time these finished (or abandoned) projects are not worth keeping around. Bitbucket offers free unlimited private repos, so using it for archiving projects seems like a great option.

Here’s the easy guide to archiving (or moving) a project from Github to Bitbucket.

Archive a Github Repo on Bitbucket by omarrr

1. Import the Github repository to Bitbucket

Probably the easiest part. Bitbucket has implemented a flawless Import your GitHub repositories feature. Authenticate with Github and you are done (Bitbucket will send out an email once the import is complete). If your project was private in Github it’ll still be private once it gets ported to Bitbucket.

2. Add the new Bitbucket remote on your local machine

This will allow you to use bitbucket as another remote should you want to continue doing development.

git remote add bitbucket <https://omarrr@bitbucket.org/omarrr/PROJECT>

Check your setup to make sure all is good.

git remote -v

    bitbucket   https://omarrr@bitbucket.org/omarrr/PROJECT.git (fetch)
    bitbucket   https://omarrr@bitbucket.org/omarrr/PROJECT.git (push)
    origin  git@github.com:omarrr/PROJECT.git (fetch)
    origin  git@github.com:omarrr/PROJECT.git (push)

3. Setup the new origin repo

If you are going to delete the repo from Github and —potentially— start using Bitbuket instead, you’ll want to setup origin to point to the new Bitbucket remote instead of Github. We do this so that we can keep working with the new repo as if it was the old one by pushinng and pulling to Bitbucket as the default remote.

git remote rename origin github
git remote rename bitbucket origin

Again, check that everything is good

git remote -v

    github  git@github.com:omarrr/PROJECT.git (fetch)
    github  git@github.com:omarrr/PROJECT.git (push)
    origin  https://omarrr@bitbucket.org/omarrr/PROJECT.git (fetch)
    origin  https://omarrr@bitbucket.org/omarrr/PROJECT.git (push)

4. Done!

Since your project is safe in Bitbucket now, you can delete it from Github. You can see below how to.

4.1. Create a backup or clone (Optional)

Clone your repo to retrieve a copy of the full history of your project with all branches, tags, etc.

git clone <https://omarrr@bitbucket.org/omarrr/PROJECT>

Generate a ZIP

tar -cf <PROJECT>.ZIP <PROJECT/>

Delete the clone

rm -rf <PROJECT>

4.2 Delete the project from Github (Optional)

It’ll be a good idea to confirm that Bitbucket has been properly setup and/or create a clone of the repo (see above) before proceeding (just saying).

Go to the “Danger Zone™” in the project settings page on Github (eg: https://github.com/omarrr/PROJECT/settings) and click “Delete this Repository”.

Finally remove the remote from your local machine

git remote rm github

Once more, check that everything is good

git remote -v

    origin  https://omarrr@bitbucket.org/omarrr/PROJECT.git (fetch)
    origin  https://omarrr@bitbucket.org/omarrr/PROJECT.git (push)    

5. Done!

No, really. We are done now.

Creative Coding with Cinder & Xcode – Getting Started

Of all the “creative coding” languages out there I’ve decide to give Cinder a try.

I could go back to Actionscript but that’s still a few years away from feeling like coding a vintage language. I could try again Processing but I feel like Processing still needs to graduate to the next level. I’ve heard of VVVV (or ‘V4’) and, even though, it feels refreshing to try a node-base language, it seems to me that the node metaphor is best suited for VJs but not for non-real-time coding. So then we have OpenFrameworks and Cinder. Since I’m new to both, and Cinder seems to be more actively developed these days, I’ll give it a try.

Cinder?

Cinder is a free, opensource library for creative coding, originally created by the Barbarian Group.

In their own words:

Cinder provides a powerful, intuitive toolbox for programming graphics, audio, video, networking, image processing and computational geometry. Cinder is cross-platform, and in general the exact same code works under Mac OS X, Windows and a growing list of other platforms — most recently the iPhone and iPad.

Running the sample projects

I’m using Mountain Lion but Cinder should work on previous versions of the Mac OS.X. I have upgraded Xcode, which now must be done through the app store, or else random errors might popup (thanks Apple). All Cinder development in the Mac takes place inside Xcode.

Step #1 – Download Cinder for Mac: http://libcinder.org/download/

Step #2 – Try to run a sample demo
Cinder comes with a welcome guide, sample demos and a tutorial. When I first tried to run the demos I got the following error when launching the .xcodeproj file:

It turns out that the Cinder demos and tutorials target 10.5 OS and Xcode under Mountain Lion is not happy about that. In order to get these projects running you must have the SDK for the OS you are targeting. My Xcode setup had SDKs for 10.7 and 10.8.

You’ll find the configurations paths to change under:

Project/BuildSettings/Architecture/Base SDK/



Targets/Build Settings/Architecture/Base SDK/



With those fixes in place all the Cinder XCode project should work

Starting a project from scratch

The easiest way to start a new project is using the TinderBox app, found in the tools folder. Since you can install the Cinder library on any folder the TinderBox requires the user to point to the folder where the Cinder library is to be found.

The TinderBox app creates simple apps to create standard desktop apps, IOS apps and screensavers. It is definitely the easiest to start a new project since it takes care of setting up all the dependencies, SDK paths, libraries, etc.

The basic structure of a Cinder app

First of all, Cinder is written on C++. It’s years I write C or C++. We have to deal with pointers (yuk) and the separation of declaration (header files) and definition (source files). Besides that, C++ is object oriented and really fast (great for interactive visualizations, managing large number of objects, large sets of data, video processing, etc).

A Cinder app has three main functions. These functions will look very familiar to those that have used Processing before. They basically define the elements of the app and then the routines to be executed on an endless loop. Cinder, like Processing, runs an infinite loop where graphics can be updated to create animations and interaction.

  • setup() where the initialization takes place (similar to Processing’s setup)
  • update() called every frame of the execution loop, intended to handle your calculations
  • draw() similar to update in that it gets executed once per frame, but intended to deal only with graphics

(image via http://libcinder.org/docs/v0.8.4/anatomypage.html)

Having both update and draw function allows for separation of logic and presentation layer, while keeping the main app loop very simple.

And… go!

That cover all the basics. The Hello, Cinder tutorial is a good place to see some of the possibilities of the language.

Launch Sublime Text from the command line

To file under 1-minute-fixes.

I find it extremely helpful to open files directly from the command line while in Terminal. Sublime Text —unlike TextMate— doesn’t set up a command for this, but this is easy enough to fix.

Sublime Text Logo Icon by omarrr

The documentation explains how to create a link to sublime in your local bin via:

$ ln -s "/Applications/Sublime Text 2.app/Contents/SharedSupport/bin/subl" /usr/local/bin/subl

which allows you to open files from the terminal like this:

$ subl ~/.profile

Done!

Text Mode for Chrome

There is so much clutter in many of the sites I visit (social plugins, banner ads, and all kinds of visual noise) that it is becoming increasingly hard to concentrate to read articles or even find the text on the page. So, to give me back some peace and zen, I made Text Mode, a little buddy for Chrome.

Text Mode is a Chrome extension that allows users to browse the web without distractions via clean simple text based pages.

Text Mode for Chrome

Text Mode declutters the web by loading all pages in text form (no images, animation or video) so content is easier to scan and read.

This is how the landing page for the International Herald Tribune looks like when Text Mode is enabled. Who needs images of bad news anyways?

Text Mode for Chrome

Here are some key features:

  • View text only pages
  • Images, Video, flash, are never loaded
  • Color-free pages are easier on the eye
  • Reduce pages load
  • One-click easy access
  • Removes 99% of the ads with no extra software

You can install the
Chrome Extension
or fork the
GitHub Repo.

That’s all.