【问题标题】:Simultaneous use and sharing of public methods - right approach?同时使用和共享公共方法——正确的方法?
【发布时间】:2019-06-10 05:29:53
【问题描述】:

正如标题所说,假设我有一个 class 和许多 methods 和其中的 80%:

  • 我还需要建立一个公共(1:1 功能)
  • 他们互相利用

就未来的扩展和测试而言,哪种方法最好?当然,下面的例子是微不足道的,但让我们假设我的课程里面有 20-30 个方法。如果有帮助,该项目是用 ReactJS 编写的。

方法一:

这种方法对我来说是最快的。

  • 无代码重复
  • 我在class内部使用functions,也在外部共享
  • 某些功能依赖于其他功能

class Approach1 {
  names = [];

  /* Establish methods for users also */
  publicApi = {
    check: this.check,
    setValue: this.setValue
  };

  /**
   * Public method 1
   * @public
   * @param {string} name
   * @returns {boolean}
   */
  check = name => name === "foo";

  /**
   * Public method 2 using internally method 1
   * @public
   * @param {string} name
   * @returns {boolean}
   */
  setValue = name => {
    if (this.check(name)) names.push(name);
  };
}

方法2:

我认为这种方法不好。

  • 代码重复
  • 我在class内部使用functions,也在外部共享
  • 函数不相互依赖

class Approach2 {
  names = [];

  /* Establish methods for users also */
  publicApi = {
    check: this.check,
    setValue: this.setValue
  };

  /**
   * Public method 1
   * @public
   * @param {string} name
   * @returns {boolean}
   */
  check = name => name === "foo";

  /**
   * Public method 2 with own implementation
   * @public
   * @param {string} name
   * @returns {boolean}
   */
  setValue = name => {
    if (name === "foo") names.push(name);
  };
}

方法 3:

这种方法看起来更好,但我看到很多额外的代码。

  • 附加代码(我需要封装几乎所有私有方法)
  • 我将相同的 functions 分隔为私人和公共
  • 私人method可以相互依赖
  • 公共methods 始终依赖于私人methods

class Approach3 {
  names = [];

  /* Establish methods for users also */
  publicApi = {
    check: this.check,
    setValue: this.setValue
  };

  /**
   * Private method 1
   * @private
   * @param {string} name
   * @returns {boolean}
   */
  _check = name => name === "foo";

  /**
   * Private method 2
   * @private
   * @param {string} name
   */
  _setValue = name => {
    if (this._check(name)) names.push(name);
  };

  /**
   * Public method 1 (encapsulating private method)
   * @public
   * @param {string} name
   * @returns {boolean}
   */
  check = name => _check(name);

  /**
   * Public method 2 (encapsulating private methods 1 and 2)
   * @public
   * @param {string} name
   */
  setValue = name => {
    if (this._check(name)) this._setValue(name);
  };
}

感谢您的任何提示:)

【问题讨论】:

    标签: javascript oop


    【解决方案1】:

    方法 1 看起来完全没问题。您首先需要考虑的 - 是公共合同。某些公共功能是否在内部使用另一个公共 - 不重要。因为您仍然需要测试每个公共 API。

    附言在一个类中包含 20-30 个公共方法 - 是重新考虑设计并将类拆分为多个类/模块以符合 Single Responsibility Principle 的好时机:)

    【讨论】:

      猜你喜欢
      • 2015-12-17
      • 2012-12-05
      • 1970-01-01
      • 1970-01-01
      • 2011-04-19
      • 1970-01-01
      • 2019-06-27
      • 1970-01-01
      • 2020-09-22
      相关资源
      最近更新 更多