Telerik blogs
JavaScriptT2 Dark_1200x303

How can the module design pattern help JavaScript developers? Let’s take a look.

As developers, we’re always striving to write clean and readable code. While solving many problems using technology, writing clean code is a must-do for every developer because it can save tons of resources, time and money in the future.

Design patterns allow developers to communicate better by providing a proper way of testing, implementing and maintaining code. Many design patterns can be used to help developers write better code.

For every programming language, there are design patterns that were created throughout the years, based on the experience of many developers. Design patterns are proven solutions, tested many times, that improve communication and make code reusable.

JavaScript has many design patterns that can be used to improve code. There are three main categories of design patterns—creational, structural and behavioral. Each category has many different design patterns that can be used to solve a specific problem.

We’re going to cover more about the module pattern, what it does and how it can be used in modern JavaScript applications to increase reusability and make the code clean.

Module Pattern

Making your application reusable is the best to ensure that it will have rich, well-written code. We should always ensure to write the best code possible and the module pattern can help us with that.

JavaScript does not have built-in support for modules, but the community has created impressive work-arounds. The two most popular standards are:

  • CommonJS modules: The dominant implementation of this standard is in Node.js (Node.js modules have a few features that go beyond CommonJS). It has compact syntax, designed for synchronous loading and it is mainly used on the server side.
  • AMD: The most popular implementation of this standard is RequireJS. It has a slightly more complicated syntax, enables AMD to work without eval, is designed for asynchronous loading and is mainly used on the client side.

The module pattern is a design pattern used for improving the maintainability and reusability of the code by creating public and private access levels. Sometimes called encapsulation, it protects the value inside a module from being accessed from other scopes.

The module pattern keeps the privacy of the state and organizes using closures. It protects the pieces from the global scope, avoiding possible errors and conflicts.

The module pattern is quite similar to an IIFE (immediately invoked functional expression), but a module always returns an object instead of a function.

There’s no way to define whether a function, variable or any other structure should be global or private in JavaScript. We don’t have access modifiers (keywords in object-oriented languages that set the accessibility of classes, methods and other members) in JavaScript, and this is why the scope is very important.

Usually, this is how a module pattern is defined:

(function() {
    // The private variables or functions goes here.


    return {
        // We return the variables or functions here.
    }


})();

Noticed that we’re using an IIFE and returning an object instead of any other value.

We can define a module as a function also. Let’s take a look at the following code:

const createSupplier = (function() {
  const name = "General Motors";
  const field = "automobile";


  return {
    name,
    field
  };
})();


createSupplier.name;
createSupplier.field;

We defined a function, using IIFE inside it, that returns an object. We’re simply returning an object with name and field. We can access and pass each property of the response object to a new variable.

Now, imagine that we define a new variable inside our function and we want it to be private—that means there’s no way we can access it outside the scope of the function.

const createSupplier =(function() {
  const name = "General Motors";
  const field = "automobile";


  return {
    name,
    field
  };
})();


createSupplier.name;
createSupplier.field;
createSupplier.year;

The code outside our module scope can’t access the value of year. This is how the module pattern can keep values private.

Private Methods

We can use the module pattern to create private methods. As we know, we don’t have access modifiers in JavaScript but we can use the power of closures to create private methods. Look at the following code:

const createSupplier = (function () {
  const name = "General Motors";
  const field = "automobile";


  const getSupplierName = () => name;


  return {
    name,
    field,
    getName: () => getSupplierName(),
  };
})();


createSupplier.name;
createSupplier.field;
createSupplier.getName();

Because we’re not returning our private method, it is not available outside the module. We can only use the public method, which is the publicGetName function, to return the name. This gives us the ability to create encapsulation within our code.

Revealing Module Pattern

The revealing module pattern is an improvement made to the module pattern where we write the entire object logic in the private scope of the module and the public parts are exposed by returning an anonymous object.

const createSupplier = (function () {
  // Private
  const name = "General Motors";
  const field = "automobile";
  const getSupplierName = () => name;
  const getSupplierField = () => field;


  // Public
  return {
    name,
    field,
    getName: () => getSupplierName(),
    getField: () => getSupplierField(),
  };
})();


createSupplier.name;
createSupplier.field;
createSupplier.getName();

The revealing module pattern is much easier to use and modify. The purpose of the revealing module pattern is to maintain encapsulation and reveal certain variables and methods returned in an object literal.

Conclusion

Developers are always interacting with and creating design patterns, even when they don’t realize it. The module pattern is yet another way of declaring and making reusable code.

Modules are an important piece of every modern application. They help us to organize and structure our codebase in a better way. When we’re writing code, breaking our code into small and manageable modules makes a difference in how our application is going to scale.


Leonardo Maldonado
About the Author

Leonardo Maldonado

Leonardo is a full-stack developer, working with everything React-related, and loves to write about React and GraphQL to help developers. He also created the 33 JavaScript Concepts.

Related Posts

Comments

Comments are disabled in preview mode.