Pure vs Impure methods ES6 classes. Should I pass the values around or should I store them in the object

huangapple 未分类评论52阅读模式
英文:

Pure vs Impure methods ES6 classes. Should I pass the values around or should I store them in the object

问题

以下是翻译好的内容:

我对这个主题之前进行过讨论,但我没能在Google上进行适当的搜索,所以我就在这里。

通常在编写类时,我会有一些特定的方法来执行某些操作,在方法内部我会按照以下方式组织每个步骤:

  1. MyClass {
  2. ......
  3. 主方法() {
  4. this.运行验证();
  5. const val1 = this.方法1();
  6. const val2 = this.方法2();
  7. const val3 = this.方法3(val1, val2);
  8. const val4 = this.方法4(val1, val3);
  9. ......
  10. 返回 最终结果
  11. }
  12. }

我选择仅在当前对象中存储一些特定的值。也许这样更好,或者我在更多的地方使用它并且更容易访问,这取决于情况。

我的问题是哪种做法更好。是我刚才展示给你的那种,还是像下面这段代码中的那种:

  1. MyClass {
  2. ......
  3. 主方法() {
  4. this.运行验证();
  5. this.方法1()
  6. this.方法2()
  7. this.方法3()
  8. ......
  9. 返回 this.最终结果
  10. }
  11. }

在这种情况下,我是否应该不断地更改当前对象的属性?

英文:

I am 100% sure this topic was discussed before but I didn't manage to give a proper search on google so here I am.

Usually when I am writing classes I have a specific methods which does something and inside it I structure each step like this:

  1. Class MyClass {
  2. ......
  3. mainMethod() {
  4. this.runValidation();
  5. const val1 = this.method1();
  6. const val2 = this.method2();
  7. const val3 = this.method3(val1, val2);
  8. const val4 = this.methid4(val1, val3);
  9. ......
  10. return finalResult
  11. }
  12. }

and I chose to store in the current object only some specific values. Maybe it is better this way, or maybe I am using it in more places and it is easier to access, it depends.

My question is what would be a better practice. The one I just showed you above, or the one like in the following piece of code:

  1. Class MyClass {
  2. ......
  3. mainMethod() {
  4. this.runValidation();
  5. this.method1()
  6. this.method2()
  7. this.method3()
  8. ......
  9. return this.finalResult
  10. }
  11. }

where I am constantly changing the properties of the current object?

huangapple
  • 本文由 发表于 2020年4月4日 06:04:37
  • 转载请务必保留本文链接:https://java.coder-hub.com/61021107.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定