1

I'm currently working on a library that needs to have basic management for cookies (get and set). I could use js-cookie, but I try to avoid dependencies.

I was wondering what was the best approach to deal with this. Here are the different implementations I have thought of, but I'm not sure which one is more relevant, or maybe there is a better way to do it.


1. With two separate functions

export function getCookie() {
    // code
};

export function setCookie() {
    // code
};

2. With a function and 2 methods

export function Cookie {
    this.get = function () {
        // code
    };

    this.set = function () {
        // code
    };
}

3. With a class and 2 methods

A. Classic way

export class Cookie {
    get() {
      // code
    };

    set() {
      // code
    };
}

B. Export the instance

class Cookie {
    get() {
        // code
    };

    set() {
        // code
    };
}

export new Cookie();

C. With static methods

export class Cookie {
    static get() {
        // code
    };

    static set() {
        // code
    };
}

Having your opinion will be really appreciated.

1 Answers1

0

Cookies are global, so we'll assume you do not need multiple instances of an object with methods. That rules out solutions #2 and #3A. It also rules out #3B.

If you just want to create two functions, there's absolutely no reason to place them on a class, so don't use solution #3C either. Go with solution #1, which is the simplest and most efficient.

Bergi
  • 630,263
  • 148
  • 957
  • 1,375
  • After reading the solution of your first link, I wonder if this alternative option to 1 is pertinent: exporting an object literal in which I stored the two functions? – Eric Giovannetti Jun 04 '20 at 03:45
  • It's doable, but I would advice against it. Exporting named functions is cleaner. If you want to call them like methods on an object, you still can choose to do so individually by using a namespace import: `import * as cookie from '…'; cookie.get()` (while at the same time allowing `import { get as getCookie } from '…'` in other modules). – Bergi Jun 04 '20 at 07:20