方法重载标准协议?
如果为方法添加第三个签名,是让第二个和第三个变体直接调用第一个(实现的变体),还是让第三个调用第二个,第二个调用第一个。
在我看来,额外的方法调用将是您可以忍受的开销,因此您希望所有方法都直接调用已实现的方法。
我想知道是否有人知道执行此操作的任何“标准推荐方式”,或者它是否更个人偏好或取决于上下文。当我向现有的重载方法添加新签名时,我总是想知道这一点。您几乎总是可以选择采取哪种方式。
可悲的愚蠢示例:
现有方法:
public String concatenate(String one, String two, String three) {
return(one+two+three);
}
public String concatenate(String one, String two) {
return(concatenate(one, two, ""));
}
要添加下一个方法,我要做:
public String concatenate(String one) {
return(concatenate(one,"",""));
}
或
public String concatenate(String one) {
return(concatenate(one,""));
}
,是的,我知道最终方法本质上是无操作。
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(String 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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
如果可能的话,我更喜欢创建一个所有其他重载器都调用的私有方法。
I prefer, when possible, to create a private method that all the other overloaders call.
我通常会用更少的参数进行重载,调用更多参数的重载,并填充默认值。我怀疑我通常会尽量避免重复默认值,所以我会让你的第三个变体调用第二个变体,这将调用第一个变体。不过,这绝对取决于具体情况。在某些情况下,性能将是一个重要因素,尽管通常可读性更为重要。在大多数情况下,我怀疑可读性会有非常差异,特别是在默认值很简单的情况下。
当然,在某些情况下,重载不是以这种线性方式构造的:可能有多个重载,它们都调用相同的“核心”重载,但如果它们提供不同的参数,则它们不能互相调用。
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.