简体   繁体   中英

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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