Naming of overloaded methods - singular or plural?

812 Views Asked by At

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.

2

There are 2 best solutions below

2
On

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:

Basket.addItem(n);      // add a single item
Basket.addItem([n, m]); // add multiple items
Basket.getItem();       // retrieve a single item
Basket.getItem(5);      // retrieve an array of up to 5 items
Basket.removeItem();    // remove a single item
Basket.removeItem(2);   // remove up to two items
Basket.emptyItems();     // remove them all

Unless you're already using add(), get(), remove(), of course.

2
On

If the argument is a list (array), then it's obvious that you are adding several elements. If the argument is a single instance of the element you are adding, the same thought applies.

add( Array elements):
    foreach element e
        _items[lastindex] = e

add( Element element):
    _item[lastindex]= e

That is my opinion. For reference you have:

Java List interface and
Java coding conventions

Different languages have different conventions, but the conventions outlined here are generally sane for other languages too (although, it doesn't quite answer your question).