0

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
Jason Allshorn
  • 1,625
  • 1
  • 18
  • 27
  • You *can*, but it's definitely a bit confusing to have a standalone function named `` and to also have a property of an object with the same name ``. Note that your `canUpdateScore` and your `updateScore` functions do not actually update the score - they return an *object* which has a *property* that, if called, updates the score. Maybe `makeUpdateScoreObj` would be a bit more accurate – CertainPerformance Aug 04 '18 at 22:45
  • You can use whatever names you like (it's JS, there are no rules!), but your second code snippet reads more easily. – Zac Anger Aug 04 '18 at 22:47
  • @CertainPerformance I like your point. I read more on MDN about objects when using Object.assign. I should remember that if a property carries an object, it is a reference to that object and not a new copy. – Jason Allshorn Aug 05 '18 at 08:51

1 Answers1

1

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.

Slava Knyazev
  • 5,377
  • 1
  • 22
  • 43