kkkkkkk
kkkkkkk

Reputation: 7748

When should I create a new object in Javascript?

I use this package mailgun-js to send email. First I need to create a new instance of mailgun then use it to send email, this is a simple version of my code:

const mgInstance = mailgun({
  apiKey: '...',
  domain: '...',
});

function sendMail1() {
  mgInstance.messages().send(/* ... */);
}

function sendMail2() {
  mgInstance.messages().send(/* ... */);
}

This code works fine. I just wonder if I move the code used to create new mailgun instance inside each functions, like this:

function sendMail1() {
  const mgInstance = mailgun({
    apiKey: '...',
    domain: '...',
  });

  mgInstance.messages().send(/* ... */);
}

function sendMail2() {
  const mgInstance = mailgun({
    apiKey: '...',
    domain: '...',
  });

  mgInstance.messages().send(/* ... */);
}

My question is: are there any differences between these implementation? is there a better one between them?

Upvotes: 0

Views: 60

Answers (1)

MaxArt
MaxArt

Reputation: 22627

Given that the mailgun factory function is lightweight enough, I would use a wrapper factory:

function getMailerInstance() {
  return mailgun({
    apiKey: '...',
    domain: '...'
  });
}

function sendMail1() {
  const mgInstance = getMailerInstance();

  mgInstance.messages().send(/* ... */);
}

This way, you can also easily switch to a singleton pattern, or do other computational logic before calling mailgun and so on.

I would also create a generic sendMail function that deals with... well, sending mails, and let other functions call that instead of using Mailgun's API directly. So, if you need to switch your mail API, you just need to change a small portion of your code (namely, getMailerInstance and sendMail).

Also notice how I used the generic name getMailerInstance instead of getMGInstance, which binds your code to Mailgun.

As a plus, consider returning a Promise in getMailerInstance.

Upvotes: 1

Related Questions