This question is about conventions.
Let's say I have an object Basket
that store various items in some private property (Basket._items
). Now, I want to have a couple of methods for adding, removing and getting items.
Each method can take either a single item or a list of items as an argument, or with no arguments, in the case of removing and getting, may remove or return all items.
How should I name my methods?
addItem
or addItems
removeItem
or removeItems
getItem
or getItems
(They don't all have to be the same form; for instance, maybe only the last one should be plural.)
EDIT: Generic names like add and get don't fly since semantically I'm not adding or getting Baskets; also the object is used to hold other stuff as well. I'd consider using something like Basket.items.add()
, but it's not optimal since the actual item objects also has to be stored and Basket.items._items
or Basket.items._contents
look bad. I'd still like to get more answers on my original question.
First guideline is to use conventions that match code you've already written for the project in question.
Second guideline is to choose names that make the best intuitive sense for the most common use of the method. If the default/common/no-parameter use is to retrieve a single item, then go with the singular name instead of plural.
Third guideline is to match the other code conventions you're already using in third-party libraries. For example, if you know that people using your library are using jQuery, then their conventions might be good to follow.
Since Javascript is such a dynamic language, it is typical to be 'lazy' in your method signatures. So you could use:
Unless you're already using
add()
,get()
,remove()
, of course.