0

When faced with a class that has multiple similar methods operating on different parameter types, do you include some kind of description of the parameters in the method name, or do you keep the name the same and trust that the parameters themselves provide enough information? Contrast the two examples given below:

interface Option1 {
    update(ObjectA);
    update(ObjectB);
    update(List<Object>);
}

interface Option2 {
    updateA(ObjectA);
    updateB(ObjectB);
    updateAll(List<Object>);
}

I've heard the following arguments:

  • Option 1 is better as it does not contain redundant information
  • Option 2 is better as the code is more readable and easier to maintain
Zecrates
  • 2,952
  • 6
  • 33
  • 50

2 Answers2

1

It depends. Method overloading exists because it is useful. However, it can also cause you grief.

If you are considering overloading, consider:

  • Do the methods address different concerns?
  • Will readability be impaired -- will a reader be able to tell which method is being called?
  • Is it possible that your interface may be mixed in with others with similar method names?
  • Is it possible that arguments implement more than one of the parameter types? If so, ambiguity may result, and the compiler may require you to address it.

For example:

  • Java's String.indexOf() is overloaded. All the overload have the same intent. There will be no additional indexOf() methods mixed into the leaf class.
  • setX() methods are typically not all named set() -- all of the above questions may be answered "yes."
Andy Thomas
  • 84,978
  • 11
  • 107
  • 151
  • Thanks, I think all of your points are pretty straight forward to answer except the second one. How would you go about deciding whether readability will be impaired? If I can come back to the update example, it might or might not - it seems to depend a lot on the calling class. – Zecrates Feb 02 '11 at 13:40
  • It also depends heavily on the set of concrete classes that may implement the interface, and the sets of concrete classes that may implement the arguments. Given methods o.update(A) and o.update(B), which is called by o.update(x)? It could be the first, second, neither or ambiguous, depending on the classes of o and x. Additional arguments make it more interesting. – Andy Thomas Feb 02 '11 at 14:43
0

For a statically typed language that supports method overloading, option 1.

For dealing with object hierarchies, option 1.

For all other cases, I would suggest option 2.

My 2 cents. :)

leppie
  • 115,091
  • 17
  • 196
  • 297