简体   繁体   English

如果一个函数只在另一个函数中使用,我应该把它放在里面还是外面?

[英]If a function is only used in another function should I keep it inside or outside it?

Like in the subject.就像在主题中一样。 I have a function like below and I have quite a bit of helping functions declared within a function (twice as much than in the example) because it's the only one using them.我有一个像下面这样的函数,我在一个函数中声明了很多帮助函数(是示例中的两倍),因为它是唯一一个使用它们的函数。

My question is: should I extract those helping functions outside the function to maintain rule "Function should do one job and do it well" or it should be within?我的问题是:我应该提取功能之外的那些帮助功能来维护规则“功能应该做一份工作并做好”还是应该在内部? I also read about that higher level functions should be higher for better readability, but it somehow doesn't work (shouldn't hoisting make it work?).我还读到更高级别的函数应该更高以获得更好的可读性,但它不知何故不起作用(不应该提升使其工作?)。

const queryThings = async (body = defaultBody) => {
  try {
    (...)

    // helping functions
    const isNonTestDeal = obj => (...)
    const isNonEmpty = obj => (...)
    const replaceHTMLEntity = obj => (...)
    const extractCountries = o => (...)

    const queried = await query(...) // that one is outside this function

    const cases = queriedCases
      .filter(isNonTestDeal)
      .map(obj => {

        let countries = [(...)]
          .filter(isNonEmpty)
          .map(replaceHTMLEntity)
          .map(extractCountries)

        let data = {
          (...)
        }
       return data
      })
      .filter(obj => (...))
      .sort((a,b) => a.d - b.d)
      .slice(0, 45) // node has problem with sending data of more than 8KB

    return cases
  } catch (error) {
    console.log(error)
  }
}

If you declare the function outside, and only use it in one function, then you cause namespace pollution.如果在外面声明该函数,并且只在一个函数中使用它,那么就会造成命名空间污染。 ( What is namespace pollution? ) Thus, I would recommend keeping it inside. 什么是命名空间污染? )因此,我建议将其保留在内部。 Also, if you do so, it is easier to read as well, since it will be closer to the code where it is used.此外,如果你这样做,它也更容易阅读,因为它将更接近使用它的代码。

To address your question about hoisting, it only works if you declare your function without assigning it to a variable.为了解决您关于提升的问题,它仅在您声明您的函数而不将其分配给变量时才有效。

我认为当你在其他函数中编写函数时,内存使用比写出函数要好,但你不能在另一个函数中使用它是本地函数而不是公共函数

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

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