Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

JS – When to apply the module pattern

I have a module "badges.js", where I just have two methods: "increaseBadge" and "resetBadge".

//
// badges.js
//
function increaseBadge(badgeType, userId, value) {}

function resetBadge(badgeType, userId) {}

module.exports = { increaseBadge, resetBadge };

Does it have sense to apply the module pattern in order to offer a clean interface? Should I use an IIFE or just export an object?

I mean, this

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

const badges = Object.freeze(
  VALID_BADGES_TYPES.reduce(
    (acc, badgeType) => (
      (acc[badgeType] = {
        increase: (userId, value) =>
          increaseBadge(userId, badgeType, value),

        reset: (userId) =>
          resetBadge(userId, badgeType),
      }),
      acc
    ),
    {}
  )
);

function increaseBadge(badgeType, userId, value) {}

function resetBadge(badgeType, userId) {}

module.exports = badges;

VS encapsulating all the logic with an IIFE (does it have sens? Since I am already declaring all this related stuff in a module)

const badges = (() => {
  function increaseBadge(userId, badgeType, value) {}

  function resetBadge(userId, badgeType) {}

  return Object.freeze(
    VALID_BADGES_TYPES.reduce(
      (acc, badgeType) => (
        (acc[badgeType] = {
          increase: (userId, value) =>
            increaseUserBadge(userId, badgeType, value),

          reset: (userId) => resetUserBadge(userId, badgeType),
        }),
        acc
      ),
      {}
    )
  );
})();

module.exports = badges;

>Solution :

The point of the revealing module pattern is to create a bundle of logic without polluting the global scope with variables that are used internally.

CommonJS modules have their own scope already, so there is no point in applying the revealing module pattern inside a CommonJS module.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading