开发者

Method overloading standard protocol?

开发者 https://www.devze.com 2023-01-14 05:37 出处:网络
If you add a third signature for a method, do you make the second and third variations directly call the first (the implemented variation), or do you make the third call the second and the second call

If you add a third signature for a method, do you make the second and third variations directly call the first (the implemented variation), or do you make the third call the second and the second call the first.

It would seem to me that the extra method call would be overhead you could live without, so you'd want all the methods to call the implemented method directly.

I was wondering if anyone knows of any "standard recommended way" of doing this or if it's more personal preference or depends on context. I always wonder about it when I add a new signature to an existing overloaded method. You almost always have a choice of which way to do it.

Pathetically Stupid Example:

Existing methods:

public String concatenate(String one, String two, String three) {
    return(one+two+three);
}

public String concatenate(St开发者_Go百科ring one, String two) {
    return(concatenate(one, two, ""));
}

To add the next one, do I do:

public String concatenate(String one) {
    return(concatenate(one,"",""));
}

OR

public String concatenate(String one) {
    return(concatenate(one,""));
}

and yes, I am aware that the final method is essentially a no-op.


I prefer, when possible, to create a private method that all the other overloaders call.

private String _concatenateBase(String one, String two) 
{
    return one + two;
}


public String concatenate(String one, String two, String three) 
{
    return _concatenateBase(one+two, three);
}


I would usually make overloads with fewer arguments call overloads with more arguments, filling in default values. I suspect I'd usually try to avoid duplicating the defaults, so I'd make your third variation call the second, which would call the first. However, it definitely depends on the exact situation. In some cases performance will be a significant factor, although usually readability is much more important. In most cases I doubt that there'll be very much difference in readability, particularly if the defaults are simple.

Of course, in some cases overloads aren't structured in this linear way: there may be several overloads which all call the same "core" one, but which couldn't call each other, if they're providing different parameters.

0

精彩评论

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