简体   繁体   English

Java方法重载最佳实践

[英]Java Method Overloading Best Practice

Just wondering what is best practice where creating to methods with the same signature 只是想知道在最佳实践中创建具有相同签名的方法

case 1 情况1

public void transfer(Department department){
    this.department = department;
}

public void transfer(Department department,String postion){
    this.department = department;
    this.postion = position;
}

Case 2 情况二

public void transfer(Department department){
    this.department = department;
}

public void transfer(Department department,String postion){
    transfer(department);
    this.postion = position;
}

You avoid code duplication. 您避免代码重复。

From that point of view, option 2 is slightly better, as it prevents the repetition of that assignment. 从这个角度来看,选项2稍好一些,因为它可以防止重复执行该分配。 Typically, you do that with constructors, and then you call it constructor telescoping . 通常,您使用构造函数执行此操作,然后将其称为构造函数telescoping To get to real telescoping here, you should follow the advice from Berger and rather have the one argument method call the two-argument method. 要在此处进行真正的伸缩,您应遵循Berger的建议,而应将一个参数方法称为二参数方法。 That also communicates to the reader what setting just the Department actually leads to. 可以向读者传达部门实际导致的设置。

Beyond that: the real problem I see here is naming. 除此之外:我在这里看到的真正问题是命名。 transfer() implies that something gets transferred. transfer()表示某些内容已转移。 In reality, your method is nothing but a setter . 实际上,您的方法不过是二传手 It should be named accordingly, like setTransferDetails() . 应该相应地命名,例如setTransferDetails()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM