简体   繁体   English

JavaScript:使用专用函数还是带有参数的通用函数?

[英]JavaScript: Using dedicated functions or general purpose functions with arguments?

I wonder which approach is better for creating functions in JavaScript classes: 我想知道哪种方法更适合在JavaScript类中创建函数:

  1. Having a list of functions each dedicated to one specific operation. 具有一系列功能,每个功能专用于一个特定的操作。
  2. Having a general purpose function that takes arguments to decide what to execute. 具有通用函数,该函数接受参数来决定执行什么。

My belief is the first option provides a nice interface but may cause redundant code, and second option is clean and flexible but may become confusing to use. 我相信第一个选项提供了一个不错的界面,但可能会导致冗余代码,第二个选项是干净且灵活的,但使用起来可能会令人困惑。


I really did not know how to ask this question, so I would like to explain it by a code example. 我真的不知道如何问这个问题,所以我想通过一个代码示例来解释它。

Suppose we have these Classes for printing names of creatures. 假设我们有这些类来打印生物的名称。

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")
  }
}

This question is out of pure curiosity and maybe it's best to use both of the approaches. 这个问题纯粹出于好奇,也许最好同时使用这两种方法。 And please don't mind the funky code example I wrote, you may think of the similar structure for a class for choosing a sorting algorithm, a type of connection, creating a shape or such. 而且,请不要介意我编写的时髦代码示例,您可能会想到类的相似结构,用于选择排序算法,连接类型,创建形状等。

Thats rather a design decision, so you should ask yourself does GeneralPurposePrint really get old or is it really sometimes human and sometimes not? 那是一个设计决定,所以您应该问自己: GeneralPurposePrint真的变老了,或者有时候真的是人类的,有时不是? If not that definetly shouldn't be properties of the class. 如果不是,那绝对不是类的属性。 To reduce the redundant code of the second approach you could just pass in arguments to the method: 为了减少第二种方法的冗余代码,您可以将参数传递给该方法:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM