DEV Community

Sudharshaun Mugundan
Sudharshaun Mugundan

Posted on

1 1

Revealing module pattern is beautiful

Revealing module pattern is one of the sub pattern of the module pattern. Don't know how many people still use module pattern in javascript, and I have seen a fair amount of code which uses RMP.

So what is a module pattern anyway?

  • The public members are exposed in the return function.
  • The private members live in the closure.
function greet() {
  const name = "Natasha";
  return {
    function greetHello() {
      return `Hello ${name} ! Thanks for signing up!`;
    }
    function greetWelcome() {
      return `Hello ${name} ! Welcome back!`;
    }
  }
}
Enter fullscreen mode Exit fullscreen mode

How RMP is different from Module pattern?

  • All the functions live in the closure.
  • Only the functions that should be exposed are made public under return.
  • The return functions will not have any function definitions. It will just reference the functions in the private.
(function greet() {
  const name = "Natasha"
  function greetHello() {
    return `Hello ${name} ! Thanks for signing up!`;
  }
  function greetWelcome() {
    return `Hello ${name} ! Welcome back!`;
  }
  return {
    hello: greetHello,
    welcome: greetWelcome
  }
})();
const hello = greet.hello(); //Hello Natasha ! Thanks for signing up!
const welcome = greet.welcome(); //Hello Natasha ! Welcome back!
Enter fullscreen mode Exit fullscreen mode
  • It gives a flexibility to reference the function name with our choice. Here greetHello is the function but it is exposed as hello. This helps in a lot of scenarios, let's say you are writing an API and the module would want a function name saveDetailsToDB for understanding the logic but not anyone who wants to use the API need that information, so you can just say return {save: saveDetailsToDB} .
  • Removing the key pair from the return object would make the exposed function private. Whereas in module pattern you have to remove the function from return object.

I have been a big fan of this pattern and it is just an admiration post on how beautiful it is :P

Billboard image

Deploy and scale your apps on AWS and GCP with a world class developer experience

Coherence makes it easy to set up and maintain cloud infrastructure. Harness the extensibility, compliance and cost efficiency of the cloud.

Learn more

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

πŸ‘‹ Kindness is contagious

Please leave a ❀️ or a friendly comment on this post if you found it helpful!

Okay