Javascript - Same name for static and instance methods bad practice?

Viewed 1718

In Javascript, is it considered bad practice to give a static method and an instance method the same name?

Suppose I have a class that represents a database table (Model) and I wanted to provide 2 options for fetching some value: (1) with an id, (2) through an instance:

class Foo extends Model {

  static getById(id) {
    return Foo.query().findById(id);
  }

  static getBars(id, limit, offset) {
    return Foo.getById(id).then(foo => foo.getBars(limit, offset));
  }

  getBars(limit, offset) {
    return this.$relatedQuery('bars').range(limit, offset);
  }

}

This example uses Objection JS.

So if you already have an instance of Foo called foo, you can just call foo.getBars(10, 0), rather than Foo.getBars(fooId, 10, 0).

1 Answers

It's fine when it simplifies things for you (or considerable shortens your code or something), but of course it makes it confusing to assess which of the two ways to use. Also, what if I wanted to get a baz and a qux from an id? If I used the static method, it would need to go to the database twice. Therefore I'd rather recommend to use

class Foo extends Model {
  … // constructor
  static fromId(id) {
    return new this({bar: execute(`select bar from foo where id = ${id}`)});
  }
  getBaz() {
    return getBazFromBar(this.bar);
  }
}

so that you can do Foo.fromId(…).getBaz() instead of Foo.getBaz(id).

Related