The module pattern is described by most people as:
var module = (function() {
// private fields
var a, b, c;
// private functions
function myFunction() {}
// public data (where you expose to outside)
return {
publicFunc: function() {}
};
})();
But the above code creates a single instance of the module. Does it really have to be a singleton?
Is the code below still a module pattern?
function module() {
// same code
return {
publicFunc: function() {}
};
}
Yes, a module pattern returns a singleton, but that's not really a practical limitation. You can use a module pattern to return a singleton factory function, and then invoke that factory function multiple times.
var point = (function() {
// Add private code here to make use of module pattern.
// If you don't have anything to keep private, then
// module pattern is overkill, as noted in the comments
return function(x,y) {
return {
x : x,
y: y
}
}
})();
var point1 = point(0,0);
var point2 = point(3,4);
Without using a factory function, you can also put your module pattern inside a loop and execute it multiple times (this isn't recommended as it is grossly inefficient):
var points = [];
for (var i=0; i<4; i++){
points[i] = (function module() {
// same code
return {
publicFunc: function() {}
};
})();
}
UPDATE: Added comment inside of first example per #North and #Bergi's feedback below
Yes, modules are singletons. A car has just one engine. Creating a second one simply doesn't make sense (unless you radically change the whole design, increase the load which any struts can take, etc).
The second pattern is the "class" pattern where you have many instances that behave similarly (think a bunch of cars).
I always thought of the module pattern as the non-singleton version. In fact, I do avoid singletons as much as possible, especially if they have state. They're a nightmare from a testing perspective, especially when written as a self calling function.
For me, the module pattern is all about encapsulating state. If I only use a single instance of the module, I just call it a singleton module.
Here is an article that catches the gist of it, at least how I see it.
Related
I am trying to find best way how to create multiple instances and configure my module according Module pattern.
Currently I have
var Logger = (function () {
// Private members
var _settings = {
json: JSON,
output: console
};
// Private methods
var _log = function (info) {
_settings.output.log(info);
};
var _dump = function (info) {
_log(_settings.json.stringify(info));
};
// Change default settings
var changeSettings = function (settingsArgs) {
if (settingsArgs !== undefined) {
if (settingsArgs.json !== undefined) {
_settings.json = settingsArgs.json;
}
if (settingsArgs.output !== undefined) {
_settings.output = settingsArgs.output;
}
}
};
return {
init: changeSettings,
log: _log,
dump: _dump
};
})();
I have several questions about this pattern.
What is the best way to provide configuration to the module, I simply created setter for private settings fields, but I feel this is not the best way it can be implemented. Please suggest right approach.
How to create multiple instances of my module. As I understood, module commonly used to encapsulate global objects and logic (like singletons), so most of time only one instances of module exists, but I need to have multiple instances. In my case this can be useful for example, I can create one logger ConsoleLogger another one will be AlertLogger the difference is output, but now I can only have one instance.
Please suggest the right way to follow, I have already read a lot of articles but haven't found answers to my questions. Thanks
What you have there is Module used as an Immediately-Invoked-Function-Expressions (IIFE), because of () at the end. Therefor, you are creating instance at class definition time and you can only have a single instance. You could clone one instance and have multiple of them, but that is not a good thing to do.
If you want to have multiple instances, you should remove IIFE expression at the end. Also, you can pass settings as constructor param:
var Logger = function (settingsArgs) {};
Now, you can create multiple instances:
var consoleLogger = new Logger({output: console});
var alertLogger = new Logger({output: alert}); // change this line probably, for this to work _settings.output.log(info);
Thus far I've worked only with relatively small projects (and mostly alone), but this time I have to collaborate with other programmers... basically because of that I must plan the structure of the website very carefully for the avoidance of spending hours debugging the code.
At this point I suppose doing that in the following manner. I divide my code in modules and store each module in a separate file inside an object (or a function) with a made-up name (lzheA, lzheB, lzheC etc.) to avoid conflicts whether an object with the same name was used in an another piece of code. When the document is loaded, I declare a variable (an object) that I use as a main namespace of the application. Properties of the object are the modules I defined before.
// file BI.lib.js
var lzheA = {
foo: function() {
},
bar: function() {
},
}
// file BI.init.js
function lzheK() {
BI.loadPage();
}
// file BI.loadPage.js
function lzheC() {
var result = document.getElementById('result');
result.innerHTML = "that worked";
}
// and so on
var lzheA,lzheB,lzheD,lzheE,lzheF,lzheG,lzheH,lzheI,lzheJ;
// doing the following when the document is loaded
var BI = {
lib: lzheA,
menu: lzheB,
loadPage: lzheC,
customScripts: lzheD,
_index: lzheE,
_briefs: lzheF,
_shop: lzheG,
_cases: lzheH,
_blog: lzheI,
_contacts: lzheJ,
init: lzheK,
}
BI.init();
https://jsfiddle.net/vwc2og57/2/
The question... is this way of structuring worth living or did I miss something because of lack of experience? Would the made-up names of the modules confuse you regardless of the fact that each one used only twice - while declaring the variable and assigning it to a property?
I consider the namespaces a good option when you want to modularize applications in Javascript. But I declare them in a different way
var myModule = myModule || {}; // This will allow to use the module in other places, declaring more than one specificComponent in other js file for example
myModule.specificComponent = (function(){
// Private things
var myVar = {};
var init = function() {
// Code
};
return {
init: init // Public Stuff
};
})();
If you want to call the init method, you would call it like this
myModule.specificComponent.init();
With this approach, i guarantee that the module will not be overwritten by another declaration in another place, and also I can declare internal components into my namespaces.
Also, the trick of just exposing what you want inside the return block, will make your component safer and you will be encapsulating your code in a pretty way.
Hope it helps
I'm new to JavaScript and am trying to understand how to use namespaces to avoid naming conflicts. So far, the two most popular methods I've found for creating namespaces are these:
Method 1:
var MYAPPLICATION = {
calculateVat: function (base) {
return base * 1.21;
},
product: function (price) {
this.price = price;
this.getPrice = function(){
return this.price;
};
},
doCalculations: function () {
var p = new MYAPPLICATION.product(100);
alert(this.calculateVat(p.getPrice()));
}
}
Method 2:
var DED = (function() {
var private_var;
function private_method()
{
// do stuff here
}
return {
method_1 : function()
{
// do stuff here
},
method_2 : function()
{
// do stuff here
}
};
})();
Is the difference that the second method allows you to have private methods and variables, since only what is inside of the object being returned will be globally accessible? Which of these methods is best (or is there a better way)?
If you write an API for other people, I think method two is better. Example:jQuery.
In a web page, I prefer method one. Example:stackoverflow
In method two, you can not read and write functions and variables that is private, so if there is a bug, you can not read something by developer-tools for debug.
Second method is called 'module' pattern. Makes it comfortable for developers to use your code. Self-invoking function creates scope, so you only expose methods that you want to make public by returning object that contains references to those methods (public API). Those methods can have a lot of private helper functions and variables that you keep private for your own use. Most of the libraries are written this way. It's generally good to structure your library like that.
Here's a link to the website that explains it well : http://www.adequatelygood.com/JavaScript-Module-Pattern-In-Depth.html
First method is just the way to put all the related functions together. You can make those for personal use in your module. Example:
Calc.add(5,5), Calc.subtract(3,2), Calc.multiply(3,3);
add, subtract, multiply share same namespace because they are related.
I am new to unit testing so I might be missing something, but how am I supposed to structure requirejs modules in order to make them fully testable? Consider the elegant revealing module pattern.
define([], function () {
"use strict";
var func1 = function(){
var data = func2();
};
var func2 = function(){
return db.call();
};
return {
func1 : func1
}
});
As far as I am aware of this is the most common pattern for building requirejs modules. Please correct me if I am wrong! So in this simplistic scenario I can easily test return values and behavior of func1 since it is global. However, in order to test func2 I also would have to return it's reference. Right?
return {
func1 : func1,
_test_func2 : func2
}
This makes the code slightly less pretty, but overall is still ok. However, if I wanted to mock func2 and replace its return value by using Jasmine spy I would not be able to since that method is inside a closure.
So my question is how to structure requirejs modules to be fully testable? Are there better patterns for this situation than revealing module pattern?
Are you sure you want to test the private function func2?
I think developers are missing the point of unit tests when they try writing tests for private functions.
Dependencies are what get us by the balls when developing software. And the more dependencies the tighter the squeeze . So if you have lots of tests dependant on the internal workings of a module it's going to be really painful when you want to change the internal implementation. So keep your tests dependant on the public interface, and keep the private stuff private.
My advice:
Design the public interface to your module.
Write a test against the public interface to specify some expected behaviour.
Implement the code needed to pass that test.
Refactor (if necessary)
Repeat from step 2, until all the functionality has been defined by tests, and all the tests pass.
During the implementation and refactoring stages the internals of the module will change. For example, func2 could be split up into different functions. And the danger is that if you have tests for func2 specifically, then you may have to rewrite tests when you refactor.
One of the main benefits of unit tests is that they ensure we do not break existing functionality when we change a module's internal workings. You start losing that benefit if refactoring means you need to update the tests.
If the code in func2 becomes so complex that you want to test it explicitly, then extract it into a separate module, where you define the behaviour with unit tests against the public interface. Aim for small, well tested modules that have an easy to understand public interface.
If you are looking for help with regards to unit testing I thoroughly recommend Kent Beck's book "TDD by example". Having poorly written unit tests will become a hindrance rather than a benefit, and in my opinion TDD is the only way to go.
If functions in a module call the module's other functions directly (i.e. by using references that are local to the module), there is no way to intercept these calls externally. However, if you change your module so that functions inside it call the module's functions in the same way code outside it does, then you can intercept these calls.
Here's an example that would allow what you want:
define([], function () {
"use strict";
var foo = function(){
return exports.bar();
};
var bar = function(){
return "original";
};
var exports = {
foo: foo,
bar: bar
};
return exports;
});
The key is that foo goes through exports to access bar rather than call it directly.
I've put up a runnable example here. The spec/main.spec.js file contains:
expect(moduleA.foo()).toEqual("original");
spyOn(moduleA, "bar").andReturn("patched");
expect(moduleA.foo()).toEqual("patched");
You'll notice that bar is the function patched but foo is affected by the patching.
Also, to avoid having the exports polluted by test code on a permanent basis, I've sometimes done an environmental check to determine whether the module is run in a test environment and would export functions necessary for testing only in testing mode. Here's an example of actual code I've written:
var options = module.config();
var test = options && options.test;
[...]
// For testing only
if (test) {
exports.__test = {
$modal: $modal,
reset: _reset,
is_terminating: _is_terminating
};
}
If the requirejs configuration configures my module (using config) so that it has a test option set to a true value then the exports will additionally contain a __test symbol that contains a few additional items I want to export when I'm testing the module. Otherwise, these symbols are not available.
Edit: if what bothers you about the first method above is having to prefix all calls to internal functions with exports, you could do something like this:
define(["module"], function (module) {
"use strict";
var debug = module.config().debug;
var exports = {};
/**
* #function
* #param {String} name Name of the function to export
* #param {Function} f Function to export.
* #returns {Function} A wrapper for <code>f</code>, or <code>f</code>.
*/
var _dynamic = (debug ?
function (name, f) {
exports[name] = f;
return function () {
// This call allows for future changes to arguments passed..
return exports[name].apply(this, arguments);
};
} :
_dynamic = function (name, f) { return f; });
var foo = function () {
return bar(1, 2, 3);
};
var bar = _dynamic("bar", function (a, b, c) {
return "original: called with " + a + " " + b + " " + c;
});
exports.foo = foo;
return exports;
});
When the RequireJS configuration configures the module above so that debug is true, it exports the functions wrapped by _dynamic and provides local symbols that allow referring to them without going through exports. If debug is false, then the function is not exported and is not wrapped. I've updated the example to show this method. It's moduleB in the example.
I recently got familiar with the Revealing Module Pattern (RMP) and I've read quite a few articles about it.
It seems like a very good pattern and I would like to start using it in a big project. In the project I'm using : Jquery, KO, requireJS, Jquery Mobile, JayData. It seems to me like it'll be a good fit for the KO ViewModels.
In specific I'd like to use THIS version of it.
One thing I could not find are disadvantages for using this pattern, is it because there aren't any (I find it hard to believe)?
What should I consider before starting to use it?
The Revealing Module Pattern (RMP) creates objects that don't behave well with respect to overriding. As a consequence, objects made using the RMP don't work well as prototypes. So if you're using RMP to create objects that are going to be used in an inheritance chain, just don't. This point of view is my own, in opposition to those proponents of the Revealing Prototype Pattern.
To see the bad inheritance behavior, take the following example of a url builder:
function rmpUrlBuilder(){
var _urlBase = "http://my.default.domain/";
var _build = function(relUrl){
return _urlBase + relUrl;
};
return {
urlBase: _urlBase,
build: _build
}
}
Setting aside the question of why you would use RMP for an object with no private components, note that if you take the returned object and override urlBase with "http://stackoverflow.com", you would expect the behavior of build() to change appropriately. It doesn't, as seen in the following:
var builder = new rmpUrlBuilder();
builder.urlBase = "http://stackoverflow.com";
console.log(builder.build("/questions"); // prints "http://my.default.domain/questions" not "http://stackoverflow.com/questions"
Contrast the behavior with the following url builder implementation
function urlBuilder = function(){
return {
urlBase: "http://my.default.domain/".
build: function(relUrl){ return this.urlBase + relUrl;}
}
}
var builder = new urlBuilder();
builder.urlBase = "http://stackoverflow.com";
console.log(builder.build()); // prints "http://stackoverflow.com/questions"
which behaves correctly.
You can correct the Revealing Module Pattern's behavior by using this scope as in the following
function rmpUrlBuilder(){
var _urlBase = "http://my.default.domain/";
var _build = function(relUrl){
return this.urlBase + relUrl;
};
return {
urlBase: _urlBase,
build: _build
}
}
but that rather defeats the purpose of the Revealing Module Pattern. For more details, see my blog post http://ilinkuo.wordpress.com/2013/12/28/defining-return-object-literals-in-javascript/
I read the article that #nemesv referenced me to (Thanks :)) and I thinks there is one more disadvantage that was not mentioned, so I thought I'd add it here for reference. Here is a quote from the article:
Disadvantages
A disadvantage of this pattern is that if a private function refers to
a public function, that public function can't be overridden if a patch
is necessary. This is because the private function will continue to
refer to the private implementation and the pattern doesn't apply to
public members, only to functions.
Public object members which refer to private variables are also
subject to the no-patch rule notes above.
As a result of this, modules created with the Revealing Module pattern
may be more fragile than those created with the original Module
pattern, so care should be taken during usage.
And my addition:
You can't use inheritance with this pattern. For example:
var Obj = function(){
//do some constructor stuff
}
var InheritingObj = function(){
//do some constructor stuff
}
InheritingObj.prototype = new Obj();
InheritingObj.prototype.constructor = InheritingObj;
This a simple example for inheritance in js, but when using the Revealing Prototype Pattern (archived here) you'll need to do this:
InheritingObj.prototype = (function(){
//some prototype stuff here
}());
which will override you inheritance.