JavaScript design pattern: difference between module pattern and revealing module pattern?
Asked Answered
C

4

68

I'm reading the book Learning JavaScript Design Patterns recently. What I don't get is the difference between module pattern and revealing module pattern. I feel they are the same thing. Anyone can give an example?

Cardona answered 7/4, 2014 at 7:58 Comment(1)
S
125

There are at least three different ways to implement the Module Pattern, but the Revealing Module Pattern is the only Module Pattern descendant that has an official name.

The Basic Module Pattern

The Module Pattern must satisfy the following:

  • Private members live in the closure.
  • Public members are exposed in the return object.

But there's a lot of ambiguity in this definition. By resolving the ambiguity differently, you get variants of the Module Pattern.

The Revealing Module Pattern

The Revealing Module Pattern is the most famous and most popular of the Module Pattern variants. It has a number of advantages over the other alternatives, such as

  • Rename public functions without changing function body.
  • Change members from public to private or vice versa by modifying a single line, without changing the function body.

The RMP satisfies three additional conditions in addition to those in the original:

  • All members, whether public or private, are defined in the closure.
  • The return object is an object literal with no function definitions. All right hand side expressions are closure variables
  • All references are via the closure variables, not the return object.

The following example shows how it's used

var welcomeModule = (function(){
  var name = "John";
  var hello = function(){ console.log("Hello, " + name + "!");}
  var welcome = function() { console.log( hello() + " Welcome to StackOverflow!");}
  return {
    name: name,
    sayHello: hello,
    sayWelcome: welcome
  }
})();

If you wanted to make name and sayHello private, you just need to comment out the appropriate lines in the return object.

var welcomeModule = (function(){
  var name = "John";
  var hello = function(){ console.log("Hello, " + name + "!");}
  var welcome = function() { console.log( hello() + " Welcome to StackOverflow!");}
  return {
    //name: name,
    //sayHello: hello,
    sayWelcome: welcome
  }
})();

The Module Pattern with Object Literal

This is probably the oldest variant of the Module Pattern. Unlike RMP, there's no sexy official name for this variant.

It satisfies the following conditions, in addition to the original:

  • Private members are defined in the closure.
  • Public members are defined in the return object literal.
  • References to public members are via this, whenever possible.

In the following example, you can see how, in contrast to RMP, the function definitions are actually in the return object literal, and references to members are qualified by this.

var welcomeModule = (function(){
  return {
    name: "John",
    sayHello: function(){ console.log("Hello, " + this.name + "!");}
    sayWelcome: function() { console.log( this.hello() + " Welcome to StackOverflow!");}
  }
})();

Note that unlike RMP, in order to make name and sayHello private, the references pointing to name and sayHello in the various function body definitions also have to be changed.

var welcomeModule = (function(){
  var name = "John";
  var sayHello = function(){ console.log("Hello, " + name + "!");};
  return {
    //name: "John",
    //sayHello: function(){ console.log("Hello, " + this.name + "!");}
    sayWelcome: function() { console.log( hello() + " Welcome to StackOverflow!");}
  }
})();

The Module Pattern with Return Object Stub

This variant also has no official name.

It satisfies the following conditions, in addition to the original:

  • An empty return object stub is defined at the beginning.
  • Private members are defined in the closure.
  • Public members are defined as members of the stub
  • References to public members are via the stub object

Using our old example, you can see that public members are directly added to the stub object.

var welcomeModule = (function(){
  var stub = {};
  stub.name = "John";
  stub.sayHello = function(){ console.log("Hello, " + stub.name + "!");}
  stub.sayWelcome = function() { console.log( stub.hello() + " Welcome to StackOverflow!");}
  return stub;
})();

If you want to make name and sayHello private as before, the references to the now-private members have to be changed.

var welcomeModule = (function(){
  var stub = {};
  var name = "John";
  var sayHello = function(){ console.log("Hello, " + name + "!");}
  
  stub.sayWelcome = function() { console.log( hello() + " Welcome to StackOverflow!");}
  return stub;
})();

Summary

The differences between the Revealing Module Pattern and the other variants of the Module Pattern is primarily in how public members are referenced. As a result, RMP is much easier to use and modify, which accounts for its popularity. However, these advantages come at a great cost (in my opinion), which Addy Osmani alludes to in his post on the Revealing Module Pattern,

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 which I've talked about in some other posts.

Sericeous answered 7/4, 2014 at 16:55 Comment(11)
@I-Lin Kuo. So what's the benefit using IIFE with the namespace passed in comparing to RMP? which one is more flexiable? ;(function ( namespace, undefined ) { namespace.say = function ( msg ) { speak( msg ); }; function speak(msg) { console.log( "You said: " + msg ); } })( window.namespace = window.namespace || {} ); It seems like they work exactly same to me. Any explaination would be appreciated. ThanksHomes
The short answer is that the RMP is an anti-pattern so you shouldn't use it. The code sample you showed is more of a mixin pattern to me, so it's more flexible than the original module pattern, but both require the same understanding to execute correctly. If you pose an actual stackoverflow question, I can give a more detailed answer.Sericeous
I just read your another post here . #14051255 It seems like using Object.create() instead of new() would work just fine. what do you think? Also, I can define prototype inside RMP in this way. jsfiddle.net/d0n7kfmx let me know what you think.Homes
@I-LinKuo there are a couple of broken references in your code samples - e.g. sayHello vs helloBandbox
I'm a bit confused: In your example, if I were to use welcomeModule.name = 'James'; , console.log(welcomeModule.name) would return "James", but welcomeModule.sayHello() would output "Hello, John". But if I would expose a public method like setName = function(newName){ name = newName; } and change the name with that, I'd get still "John" with consule.log(welcomeModule.name), even though welcomeModule.sayHello(); would output the new changed name. How does that work exactly? jsfiddle.net/isaacalves/brug6bsu/3Poetize
After reading up on this, I just found that putting code from a former IIFE into an empty object {} has the same effect in all modern browsers of keeping my code out of the global namespace. Any idea what this approach is called (apart from the "empty object pattern")?Greenlee
is there a reason you use function expressions instead of function declarations in the rmp?Uriia
@ZachSmith Since you are executing the function immediately and don't need the function anymore, there is no point in declaring the function separately.Haymaker
@I-LinKuo "RMP is an anti-pattern so you shouldn't use it". Not sure how you came to that conclusion. I have never seen that anywhere. It's an information hiding pattern which makes it possible to create objects that hide their information from clients and where you cannot mutate their data. You do not need to wrap it in an IIFE either; you can reuse the function as object creators as an alternative to classes. Works fine in TS as well.Haymaker
@Haymaker A side effect of hiding the data is that the effect of overriding the public methods depends on the implementation of module pattern. If you don't override and just compose objects, no problem. Also, it's much less of a problem for cross-compiled languages like TS because the module pattern is implemented the same way.Sericeous
@I-LinKuo OK, I get you. Crockford proposes a way to do quazi-subclassing in his "Javascript: The good parts", but TBH I found it too bothersome and I only really use Revealing Module for singletons where I Object.freeze() the published interface, so they are immutable.Haymaker
C
9

Short answer, In Module pattern we define functions in returning object.

In Revealing Module pattern, we define functions in closure area and only use variable names in returning object.

Doing this simplifies the code and has lot of other advantages

Colwell answered 5/6, 2018 at 3:13 Comment(0)
K
0

Just try to do something based on top comment answer. May be it is safer if call private function by passing this to it, so private function could reference public function with this variable.

I created a revealing module pattern with following code.

var HTMLChanger = (function () {
    var privateFunc = function () {
        this.sayHello();
    }

    var hello = function () {
        console.log('say Hello');
    }
    var callPrivate = function () {
        privateFunc.call(this);
    }


    return {
        sayHello: hello,
        callPrivate: callPrivate
    };
})();

HTMLChanger.callPrivate();
//say Hello

HTMLChanger.sayHello = function() { console.log('say Hi!') };

HTMLChanger.callPrivate();
//say Hi!

As you can see we can override public member.

Krone answered 17/2, 2018 at 6:30 Comment(0)
F
-2

Both the Module Design Pattern and the Revealing Module Design Pattern are ways of structuring JavaScript code to encapsulate and organize functionality. They both aim to achieve better modularization and encapsulation, making code easier to manage, understand, and maintain. However, they have some differences in terms of how they expose and organize their methods and properties.

Module Design Pattern: The Module Design Pattern involves creating an anonymous function that encapsulates private data and methods within a closure. This creates a private scope where variables and functions are hidden from the global scope. This pattern often returns an object containing methods and properties that can be accessed from the outside, effectively acting as a public API for the module. Here's a basic example:

const Module = (function() {
  // Private variables and functions
  let privateVar = 10;

  function privateFunction() {
    console.log("Private function called");
  }

  // Public API
  return {
    publicVar: 20,
    publicFunction: function() {
      console.log("Public function called");
    }
  };
})();

console.log(Module.publicVar); // 20
Module.publicFunction(); // "Public function called"

Revealing Module Design Pattern: The Revealing Module Design Pattern is a variation of the Module Design Pattern. Instead of returning an object containing the public API, it maps private functions and properties to a public API within the closure, effectively revealing only the parts you want to make public. This can make the code cleaner and more self-documenting by showing the structure of the public methods more explicitly. Here's an example:

const RevealingModule = (function() {
  let privateVar = 10;

  function privateFunction() {
    console.log("Private function called");
  }

  function publicFunction() {
    console.log("Public function called");
  }

  // Reveal only the public parts
  return {
    publicVar: privateVar,
    publicFunction: publicFunction
  };
})();

console.log(RevealingModule.publicVar); // 10
RevealingModule.publicFunction(); // "Public function called"

In summary, while both patterns share the concept of encapsulation and module organization, the Revealing Module Design Pattern places a stronger emphasis on clearly revealing the public API by explicitly listing the public functions and variables, making it easier to see which parts are meant to be used externally. The choice between the two patterns depends on your preference and the specific needs of your project.

Fontaine answered 11/8, 2023 at 19:2 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.