开发者

Why overload a function with fewer / greater arguments?

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 i开发者_JS百科f this has any benefits or what the interviewer was getting at here. Does it have any performance advantages? Any thoughts?

Thanks.


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.


I've used this to provide backward compatibilty before.


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 }


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


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.


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 ;)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜