Revealing Module Pattern in Java Script

The Revealing Module Pattern is based on a pattern referred to as the Module Pattern. It focuses on public & private methods. The only difference is that the revealing module pattern was engineered as a way to ensure that all methods and variables are kept private until they are explicitly exposed; usually through an object literal returned by the closure from which it’s defined. it help in following ways

  • Cleaner approach for developers
  • Supports private members and functions
  • Less clutter in the global namespace
  • Localization of functions and variables through closures.
  • Syntax of our scripts are even more consistent
  • Explicitly defined public methods and variables which lead to increased readability

This pattern allows the syntax of our scripts to be more consistent. It also makes it more clear at the end of the module which of our functions and variables may be accessed publicly which eases readability.

var math = (function () {
    function addition(a, b)
    {
        return a + b;
    }
 
    function subtraction(a, b)
    {
        return a - b;
    }
 
    return {
        add: addition,
        subtract : subtraction
    };
})();

Client consuming the math module would consume in following manner.

<script >
     var a = 30;
     var b = 20;
     console.log(math.add(a, b));
     console.log(math.subtract(a, b));
 </script>

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.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s