简体   繁体   中英

Can I use the same function names when using Object.assign() in composition?

Context

I created a new object using a composition paradigm in Javascript.

const canUpdateScore = (state) => ({
    update: (spell) => state.score-- 
})

const mage = (name) => {
  let state = {
    score: 100,
  }
  return Object.assign(state, canUpdateScore(state));
}

scorcher = mage()
scorcher.update();    // call the update method
console.log(scorcher.score)    // 99

Question

Would it be confusing to name the assiging method the same as the external function that is returning that method(example below)?, or is it better to use different names (in context above)?

const updateScore = (state) => ({
    updateScore: (spell) => state.score-- 
})

const mage = (name) => {
  let state = {
    score: 100,
  }
  return Object.assign(state, updateScore(state));
}

scorcher = mage()
scorcher.updateScore();    // call the update method
console.log(scorcher.score)    // 99

The convention for using composition is "thing-doer". Your updateScore composant is a "scoreUpdater" and it "updateScore"'s.

Would write out like this:

const scoreUpdater = (state) => ({
    updateScore: (spell) => state.score-- 
})

Now, update on it's own a rather lousy name both for clarity reasons and for design ones as well. Imagine you thing of another composant which will update the health: healthUpdater which also implements an update method. One of them will override the other.

In general, names of properties in composants should in some way, explicitly refer to the composant itself.

canUpdateScore is definitely a poor name for an object regardless are it implies a boolean, which is not the case.

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