views:

88

answers:

6

So I am a java programmer and I know what overloading a function means. Moreover, I have overloaded a function with different type of arguments, and can overload with, fewer and greater arguments.

I was asked this on an interview. I really don't know if this has any benefits or what the interviewer was getting at here. Does it have any performance advantages? Any thoughts?

Thanks.

+6  A: 

It is about providing a flexible interface by allowing the functions to be called with default values. Some languages allow this via optional parameters, but you can achieve more or less the same with overloads.

Brian Rasmussen
+4  A: 

I've used this to provide backward compatibilty before.

Simon Catlin
A: 

The interviewer may have been hinting at dependency injection, which can be done through methods or constructors.

jeffo
A: 

Definitely for backward compatibility. Also if few parameters are very rarely passed (more than 2) with non default values, then it is useful to create overloaded methods.

fastcodejava
+1  A: 

its to provide flexibility eg

say you have a proerty that usually doesnt need to be changed thexcept in special circumstances you could simply write an overloaded method to accept the special curcumstance instead of requiring it to be defaulted or requiring setting it everytime in the regular method

for example

public void connectToDatabase(string connString) { //some commands }

public void connectToDatabase(string connString, string username, string password) { //some commands }

Chris McGrath
A: 

If a language does not support overloading, then the execution is faster. Because the program will not have to use/track/manage the overloading mechanism.

But if the language support overloading, you should USE them! Here goes the reasons in sense of performance:

  1. Passing parameters are costly. Because they needs memory spaces and access to them. So if you send 2 parameters of the SAME data type, it will practically be slower than if you may pass 1 parameter.

  2. For different parameters, you have no way out.

  3. As you will at least have to make the function for the longest parameter list, you will have to check a lot of null/empty values and have conditions depending on them to implement the algorithm for fewer or different arguments.

  4. There are some arguments which are actually attributes of other arguments. You can send them in an array, or an array reference. Like you may want to print something and you may have some arguments like color, border, etc which are common to them. You really don't need to make single parameters for them.

  5. You should also count how many times each version is used. You can merge ones that may have lower frequencies. Don't touch the busiest ones!

    So a lot of practical theories ;)

Muktadir