【问题标题】:JavaScript: Using dedicated functions or general purpose functions with arguments?JavaScript:使用带参数的专用函数或通用函数?
【发布时间】:2018-12-29 19:02:18
【问题描述】:

我想知道哪种方法更适合在 JavaScript 类中创建函数:

  1. 有一个函数列表,每个函数都专用于一个特定的操作。
  2. 有一个通用函数,它接受参数来决定执行什么。

我的信念是第一个选项提供了一个很好的界面,但可能会导致冗余代码,第二个选项干净灵活,但使用起来可能会变得混乱。


这个问题我真的不知道怎么问,所以我想通过一个代码示例来解释一下。

假设我们有这些用于打印生物名称的类。

class GeneralPurposePrint {
  constructor (args) {
    this.isHuman = args.isHuman || false;
    this.isOld = args.isOld || false;
    this.name = args.name || "Nameless" 
  }

  //This is what I mean by "general purpose function"
  //arguments may as well come with the printName functions...
  printName(){
    const type = this.isHuman ? "the human" : "the animal";
    const age = this.isOld ? "Old" : "Young";

    console.log(`${age} ${this.name} ${type}`)
  }
}


class DedicatedPrint {
  constructor (name) {
    this.name = name;
  }

  //And by dedicated functions I mean the following functions here
  printOldHuman() {
    console.log("Old human", this.name, "the human")
  }

  printYoungHuman() {
    console.log("Young", this.name, "the human")
  }

  printOldAnimal() {
    console.log("Old", this.name, "the animal")
  }

  printYoungAnimal() {
    console.log("Young", this.name, "the animal")
  }
}

这个问题纯粹是出于好奇,也许最好同时使用这两种方法。请不要介意我写的时髦的代码示例,您可能会想到类的类似结构,用于选择排序算法、连接类型、创建形状等。

【问题讨论】:

  • 你会想要两者都做。制作通用函数以使您的实现干净,然后制作通用的专用函数,只需使用适当的参数调用通用函数。
  • 这真的取决于实际代码中的情况。您的代码实际上并没有真正做任何事情,我们看不到调用者如何使用它,因此我们无法真正判断什么是最好的。不要重复代码并使其对调用者友好。

标签: javascript function class ecmascript-6


【解决方案1】:

这是一个设计决定,所以你应该问问自己GeneralPurposePrint 真的会变老,还是真的有时是人类,有时不是?如果不是,那绝对不应该是类的属性。为了减少第二种方法的冗余代码,您可以将参数传递给方法:

printName(old, human) {
  console.log((old ? "Old" : "Young") + this.name + (human ? "the human" : "the animal"));
}

【讨论】:

    猜你喜欢
    • 2011-10-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多