Java Programming – When is Method Overloading Appropriate?

javalanguage-agnosticmethod-overloadingobject-oriented

Suppose I am working on an existing, reasonably large system. I have an object, myObject of class MyClass (for the example's sake, suppose I'm working in Java). myObject is a composition containing a Collection, say, a List and other objects which (I think) are irrelevant. It contains delegate methods which just serve to call upon the methods of the List it is composed of, in order to ensure the List it has is not exposed (sorry if I've got my terminology wrong).

Let's say that this List is a List<String> but, for some reason, the main access method is a mask method for class SomeOtherClass. If I wanted to insert a new value pair into my List, then I'd have an object of SomeOtherClass called someObject. I'd call myObject.insert(someObject) and inside the insert method there would be some magic that would retrieve a String to put into the List<String>.

Supposing now that I've only got a String value, and no SomeOtherClass object to insert. Assuming I can't modify the insert method because it would break everything in this system. Then should I overload the insert method? Or should I create a new object of SomeOtherClass every time I want to call insert?

I guess if I did overload it, it would look something like this…

public void insert(String s) {
    ...
}

public void insert(SomeOtherObject obj) {
    this.insert(obj.magicStringMethod());
}

(This example is a contrived puzzle based upon a similar (slightly more complex) situation regarding overloading that I encountered yesterday. I'll expand it if there's anything that was unclear)

Would this be an appropriate place to overload a method? If not, when should I overload a method?

Best Answer

You overload when you wish to support different types:

public overload void MyMethod(int value)
{ 
}

public overload void MyMethod(bool value)
{
}

public overload void MyMethod(string value)
{
}

or to support a progressive interface using different parameter lists:

public overload void MyOtherMethod()
{
    this.MyOtherMethod(DefaultValue);
}

public overload void MyOtherMethod(int value)
{
    this.MyOtherMethod(value, DefaultOtherValue);
}

public overload void MyOtherMethod(int value, bool otherValue)
{
    ...
}

You might even get a little crazy and support both different types AND a progressive interface, but you should bear in mind that you need to avoid creating variations in behaviour between overloaded methods. Each overloaded method should be functionally the same as the others in an overloaded group, otherwise it will be unclear as to how, when or why behaviour is being varied. If you want two functions to do something completely different, then you should name them accordingly.