【发布时间】: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