Coding Guru

Code never does the mistake, we make the mistakes in the code. Think, Imagine, Phrase and then Code.

The Module Pattern (Javascript)

What are Modules?


Modules are the integral piece of any application design and those keep the code a lot of organized in a project. The code is being divided into modules or element to avoid conflicts. In JavaScript, we have a tendency to do this by using the well-known module pattern or object literal notations.

The Module Pattern

This module pattern is being used to encapsulate the classes in typical software development or engineering and works around on public and private functions / methods & variables. The module pattern strives to enhance the reduction of globally scoped variables, hence decreasing the probabilities of collision with some other code throughout the application. The module pattern is tested design pattern and widely accepted in many giant projects like jQuery, Dojo, ExtJS and YUI.

What this results

It results in a reduction within the chance of your method names conflicting with some other functions declared or defined in other scripts on the page.

Privacy

The module pattern encapsulates 'privacy', state and organization by using the closures. It provides the easiest way of wrapping a combination of public and private methods and variables, protecting items from exposing into the global scope and accidentally colliding with another developer's interface. With this pattern, solely a public API is returned, keeping everything else inside the closure non-public or private. This gives non-public or private a clean solution for shielding logic doing the work while solely exposing an interface you want different elements of your application to use. Then the pattern is quite kind of like an immediately-invoked functional expression except that an object is returned instead of a function. It has to be be noted that there is not really an expressly true sense of 'privacy' within Java- Script as a result of as a result of some typical languages, it does not have access modifiers. Variables cannot technically be declared as being public nor non-public so we have a tendency to use function scope to simulate this idea. inside the module pattern, variables or methods declared are only out there within the module itself due to closure. Variables or methods declared inside the returning object but are available to everybody.

History

From a historical perspective, the module pattern was originally developed by a number of people together with  Richard Cornford in 2003. it absolutely was later popularized by douglas Crockford in his lectures. Another piece of physical object is that if you have ever played with Ya- hoo's YUI library, a number of its options might seem quite known , the reason for this is that the module pattern was a robust influence for YUI for making their components.


Examples

Let's begin staring at an implementation of the module pattern by developing a module which is self-contained.


var testModule = (function(){
var counter = 0;
return { incrementCounter : function(){
return counter++;
},
resetCounter : function(){
console.log('counter value prior to reset:' + counter );
counter = 0;
}};
})();

// test
testModule.incrementCounter();
testModule.resetCounter();

Here, different elements of the code are unable to directly scan the value of our  incrementCounter() or resetCounter(). The counter variable is truly absolutely secure from our global scope thus it acts similar to a private variable would - its existence is restricted to insidethe module's closure so the only code able to access its scope are our 2 functions. Our ways are effectively namespaced thus within the section of code, we have to prefix any calls with the name of the module (e.g. 'testModule'). When working with the module pattern, you will realize it helpful to define an easy template that you just use for getting started with it. Here's one that covers namespacing,

public and private variables:

var myNamespace = (function ()
{
var myPrivateVar = 0 ;
var myPrivateMethod = function(someText)
{
console.log(someText)
};
return
{
myPublicVar : "foo",
myPublicFunction : function(bar){
myPrivateVar++;
myPrivateMethod(bar);
}};
})();

Looking at another example, below we will see a basket implemented using the this pattern. The module itself is totally self-contained during a global variable known as JavaScript design Patterns basketModule . The basket array within the module is unbroken private so different elements of your application are unable to directly read it. It exists with the module's closure and so the only methods able to access it are those with access to its scope (ie.  addItem() , getItem() etc).
var basketModule = (function(){
var basket = [];
//private
function doSomethingPrivate(){//...}
function doSomethingElsePrivate(){//...}
return
{
//exposed to public
addItem :
function(values)
{
basket.push(values);},
getItemCount : function(){
return basket.length;
},
doSomething : doSomethingPrivate(),
getTotal : function(){ var q = this.getItemCount (),
p = 0;
while(q--)
{
p += basket[q].price ;}
return p;
}}}());

Inside the module, you may notice we have a tendency to return an  object . This gets automatically assigned  to basketModuleso that you'll interact with it as follows:
// basketModule is an object with properties which can be functions
basketModule.addItem({
item : 'bread',
price : 0.5
});
basketModule.addItem({
item : 'butter',
price : 0.3
});
console.log(basketModule.getItemCount());
console.log(basketModule.getTotal());
// however, the following will not work:
console.log(basketModule.basket);
// (undefined as not inside the returned object)
console.log(basket);

//(only exists inside the scope of the closure)
The above higher than are effectively namespaced within  basketModule

Notice how the function in the above basket module is wrapped around all of our functions, that we have a tendency to then call and immediately store the return value. This has a number of benefits including:
• The freedom to possess private functions which may only be consumed by our module. As they aren't exposed to the rest of the page, they are considered really private.
• Given that functions are declared normally and are named, it is easier to indicate call stacks during a in a when we're trying to find what function(s) threw an exception.
•As T.J Crowder has pointed out in the past, it also allows us to return different functions depending on the environment.

Advantages

We've seen why the singleton pattern can be useful, however why is the module pattern a good choice? For starters, it is a heap cleaner for developers coming from an object-oriented background than the concept of true encapsulation, at least from a JavaScript perspective. Secondly, it supports private data - so, in the module pattern, public parts of your code are able to touch the private parts, however the outside world is unable to the touch the class's privates (no laughing! OH, and due to David Engfer for the joke).

Disadvantages

The disadvantages of this  pattern are that as you access each public and private members otherwise, after you would like to alter visibility, you truly got to create changes to every place the member was used. You also cannot access non-public members in methods that are added to the object at a later point. That said, in several cases the module pattern continues to be quite helpful and once used correctly, definitely has the potential to boost the structure of your application.
Other disadvantages embrace the shortcoming to form automated unit tests for private members and extra complexity once bugs need hot fixes. It's merely not pos- sible to patch privates. Instead, one should override all public methods that act with the buggy privates. Developers cannot simply extend privates either, thus it's worth remembering privates don't seem to be as flexible as they will at first seem. Before we have a tendency to dive into how the module pattern is also enforced using completely different JavaScript frameworks, here's an easy guide for using the pattern:

var privateVar = 5 ;
// private methods
var privateMethod = function (){ return 'Private Test' ;};
return
{
// public attributes
publicVar : 10,
// public methods
publicMethod : function()
{
return ' Followed By Public Test ';
},
// let's access the private members
getData : function(){
return privateMethod() + this.publicMethod()+ privateVar;
}}
})();

Pingbacks and trackbacks (1)+

Loading