【问题标题】:Self instantiate inside static javascript class method a bad practice?在静态javascript类方法中自我实例化是一种不好的做法?
【发布时间】:2019-07-10 11:31:11
【问题描述】:

这是使用 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();
 }
}

我之所以这样写是因为我发现在 express 中使用 new Kyc(id).get(); 有点不可读。

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

任何意见都会很棒!

【问题讨论】:

  • 关于工作代码的问题可能很有趣,但它们更适合 Code Review 而不是 Stack Overflow
  • 嗯,您在创建后立即丢弃实例。 getById 将返回一个承诺,该承诺将被解析为 undefined(或被拒绝)。使新创建的实例无法访问。你打算如何使用getById
  • 好吧,不是立即,而是直到承诺得到解决:) 但希望你明白了。该实例不可访问:)
  • 这门课有什么意义?对我来说,这看起来像一个函数。
  • @Reyn 说到 OOP。作为托马斯,我不明白这门课的意义。这对我来说似乎是一个单一的功能。

标签: javascript typescript express


【解决方案1】:

在静态类方法中进行自实例化是一种不好的做法吗?

不,一点也不。将静态方法用作工厂完全没问题。

您的代码中奇怪的是您正在异步初始化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
}

【讨论】:

  • 我在使用firebase-admin 时这样做了。它从数据库的集合中获取。这就是为什么数据也存在的原因,在获取后它将从其初始结果中填充
猜你喜欢
  • 1970-01-01
  • 2018-01-20
  • 2011-06-01
  • 2021-03-23
  • 1970-01-01
  • 2011-06-19
  • 1970-01-01
  • 2017-03-21
  • 1970-01-01
相关资源
最近更新 更多