自实例化静态javascript类方法内部的不良做法?

时间:2019-07-10 11:31:11

标签: javascript typescript express

使用OOP JS(这是TS),这是不好的代码吗?

class KYC {
 public reference;
 public data = null;

 constructor(id: string) {
   this.reference = id? firestoreAdmin.collection('kyc').doc(id) :
           firestoreAdmin.collection('kyc').doc() :
 }

 async get() {
  const result = await this.reference.get();

  if(!result.exist) throw new Error('not found');

  this.data = result.data;

  return this;
 }

 static async getById(id: string) {
  return await new this(id: string).get();
 }
}

之所以这样写,是因为我发现使用 new Kyc(id).get(); 在快递中有点难以理解。

也是一个问题,这在某种程度上是一种不好的做法吗?反模式?

任何意见都很棒!

1 个答案:

答案 0 :(得分:0)

  

静态类方法中的自我实例化是不好的做法吗?

不,一点也不。将静态方法用作工厂完全可以。

代码中的怪异之处是您正在异步初始化data。那可能是有目的的,但是从我的角度来看,没有数据该类是毫无用处的,所以我建议在静态方法内部先做一遍:

class KYC {
  constructor(
    public reference,
    public data,
  ) {}

  static async getFromReference(reference) {
    const result = await reference.get();
    if (!result.exist) throw new Error('not found');
    return result.data;
  }
  static async getById(id: string) {
    const reference = firestoreAdmin.collection('kyc').doc(id);
    return new this(reference, await this.getFromReference(reference));
  }

  … // further methods operating on this.data
}
相关问题