Skip to content

Instantly share code, notes, and snippets.

@kkoziarski
Created November 28, 2014 11:12
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kkoziarski/2ce3091e8a639ff419e0 to your computer and use it in GitHub Desktop.
Save kkoziarski/2ce3091e8a639ff419e0 to your computer and use it in GitHub Desktop.
Module - The Good Parts
var serial_maker = function () {
// Produce an object that produces unique strings. A
// unique string is made up of two parts: a prefix
// and a sequence number. The object comes with
// methods for setting the prefix and sequence
// number, and a gensym method that produces unique
// strings.
var prefix = '';
var seq = 0;
return {
set_prefix: function (p) {
prefix = String(p);
},
set_seq: function (s) {
seq = s;
},
gensym: function ( ) {
var result = prefix + seq;
seq += 1;
return result;
}
};
};
var seqer = serial_maker();
seqer.set_prefix = ('Q');
seqer.set_seq = (1000);
var unique = seqer.gensym(); // unique is "Q1000"
//The module pattern takes advantage of function scope and closure to create relationships
//that are binding and private.
//The general pattern of a module is a function that defines private variables and functions;
//creates privileged functions which, through closure, will have access to
//the private variables and functions; and that returns the privileged functions or stores them in an accessible place.
//Use of the module pattern can eliminate the use of global variables. It promotes
//information hiding and other good design practices. It is very effective in encapsulating applications and other singletons.
//It can also be used to produce objects that are secure. Let’s suppose we want to make
//an object that produces a serial number.
//The methods do not make use of 'this' or 'that'. As a result, there is no way to compromise the 'seqer'.
//It isn’t possible to get or change the prefix or seq except as permitted by the methods. The 'seqer' object is mutable, so the methods could be
//replaced, but that still does not give access to its secrets. 'seqer' is simply a collection
//of functions, and those functions are capabilities that grant specific powers to use or
//modify the secret state.
//If we passed 'seqer.gensym' to a third party’s function, that function would be able to
//generate unique strings, but would be unable to change the 'prefix' or 'seq'.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment