所以我犯了一个错误。
最初为 API 编写签名时,我创建了如下内容:
public JellyBeanResult getJellyBeanReport();
现在,事实证明,由于其功能,我想重新使用更具体的 JellyBeanResult 对象,但让其他函数返回为不同进程命名的类型会令人困惑。我能想到有几种方法可以解决这个问题。我可以将返回类型重新命名为更通用的名称:
public GenericResult getJellyBeanReport();
public GenericResult getChocolateBarReport();
但这会破坏任何使用该 API 的代码。我可以创建一个新的、命名更准确的类来扩展 SpecificResult,使其更适合新函数:
public class ChocolateBarResult extends JellyBeanResult{};
public JellyBeanResult getJellyBeanReport();
public ChocolateBarResult getChocolateBarReport();
但这真的非常难看,如果我想在以后再次使用返回类型,问题仍然存在。 如何清理这些签名,使其不那么困惑,而又不会破坏任何使用它们的代码?
最佳答案
将核心功能从 JellyBeanResult 移至 GenericResult 并让 JellyBeanResult 扩展 GenericResult:
public class JellyBeanResult extends GenericResult {}
public JellyBeanResult getJellyBeanReport();
public GenericResult getChocolateBarReport();
或者如果你想完全一致:
public class JellyBeanResult extends GenericResult {}
public class ChocolateBarResult extends GenericResult {}
public JellyBeanResult getJellyBeanReport();
public ChocolateBarResult getChocolateBarReport();
关于java - 我是否应该将返回类型重命名为更通用的名称以便重用它?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2337197/