Pattern Series #1 : Revealing Module Pattern

Language: JavaScript

No ES6 classes here friends. The revealing module pattern was my first design pattern, so it felt natural to start here and give it some love. It’s been the backbone of many frameworks and can most commonly be seen used in Angular 1.X factory objects these days. With classes getting such widespread support though, and rightfully so, I wanted to come back to explore an older, yet still incredibly useful corner of object oriented development in JavaScript.

WHY?

No version of JavaScript so far has provided support for private methods, or a clean way to handle static class members consistently. Yes, your preprocessed mutant JS clone might handle them, but I mean in the actual language. With the Revealing Module Pattern, we want a way to provide and isolated scope for our logic, prevent namespace pollution, and provide a public API for our module.

HOW

The pattern is pretty straight forward to a seasoned JavaScript developer, but may seem odd to newcomers. So let’s break down what’s going on step by step.

1) First we define a self executing function. This provides our new function scope and keeps all logic isolated to one spot.

export default (()=> {

/*
* Logic here
*/


})();

2) Next we need to return a public api for our module. Object literals work wonders for this.

export default (()=> {

// Public API
return {};

})();

3) Since we now have a place for our public methods to be accessed from, we can start defining them.

export default (()=> {

function myPublicMethod() {
return 'hello';
}

// Public API
return { myPublicMethod };

})();

4) Now that we have a functioning module, we can start breaking up our public methods into smaller, more portable, private methods. Since they exist within our isolated function scope, nothing but the public methods we expose can access them.

export default (()=> {

function _myPrivateMethod() {
return 'hello';
}

function myPublicMethod() {
return _myPrivateMethod();
}

// Public API
return { myPublicMethod };

})();

Conclusion

I’ve been using this pattern for almost as long as I’ve been a professional developer and have never had it lead me astray. When you need privacy for singleton objects, this is a great path to take. It’s stable, battle tested, and reliable in every which way.

Happy coding.