Search code examples
javascriptcode-duplication

How to avoid duplicate JS code that each uses its own this?


I have several different classes with the same duplicate code. Aside from the different identity of each's this, these duplicate code are all ostensibly identical.

Here's a simplified example:

class classA {
  ...

  doSomething() {
    if (!this.id || !this.data || !this.isAllowed()) {
      return null;
    }
    return someImportedFunc(this.data, this.metadata, this.doSomethingElse());
  }
}

class classB {
  ...

  doSomething() {
    if (!this.id || !this.data || !this.isAllowed()) {
      return null;
    }
    return someImportedFunc(this.data, this.metadata, this.doSomethingElse());
  }
}

// Many other classes like this

I've thought of moving the doSomething method to another class, then importing it in all these classes. But that would result in a very messy method that takes many, many arguments to account for all the different this's. It'd look like:

class exportedClass {
  function doSomething(id, data, metadata, isAllowed, doSomethingElse) {
    if (!id || !data || !isAllowed()) {
      return null;
    }
    return someImportedFunc(data, metadata, doSomethingElse());
  }
}

class classA {
  ...

  methodThatUsesDoSomething() {
    const result = exportedClass.doSomething(
        this.id, this.data, this.metadata, this.isAllowed, this.doSomethingElse);
    ...
  }
}

Except with like 15 args instead of 5 since this is a simplified example.

How can I avoid duplicate code in this kind of situation?


Solution

  • Assuming you want a non-inheritance solution, my suggestion would be to pass "this" as an argument, as prototypes can be manipulated as parameters. That would allow you to keep the parameters at a minimum while not losing data.