代码之家  ›  专栏  ›  技术社区  ›  TwentyMiles

我是否应该将返回类型重命名为更通用的类型以重用它?

  •  2
  • TwentyMiles  · 技术社区  · 16 年前

    所以我犯了个错误。

    最初为API编写签名时,我创建了如下内容:

    public JellyBeanResult getJellyBeanReport();
    

    public GenericResult getJellyBeanReport();
    public GenericResult getChocolateBarReport();
    

    但这会破坏任何使用API的代码。我可以创建一个新的、命名更准确的类,扩展更符合新函数的SpecificResult:

    public class ChocolateBarResult extends JellyBeanResult{};
    
    public JellyBeanResult getJellyBeanReport();
    public ChocolateBarResult getChocolateBarReport();
    

    但这是真的,真的很难看,问题仍然存在,如果我想再次使用返回类型的道路上。 如何清理这些签名,使它们不那么混乱,而不破坏正在使用它们的任何代码?

    7 回复  |  直到 16 年前
        1
  •  6
  •   kem    16 年前

    将核心功能从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();
    
        2
  •  4
  •   Roman    16 年前

    任何特定的 是的

    我看到的唯一方法是您应该创建正确的方法集(如您的示例中的 GenericReport @Deprecated 注释。

        3
  •  4
  •   Joe Carnahan    16 年前

    ChocolateBarResult 延伸 JellyBeanResult 会很糟糕,因为 海蜇 可能有一些方法和字段(比如“颜色”代表果冻豆)对巧克力棒没有意义。所以,不要这样做。:-)

    创建新方法以返回正确的结果类型怎么样( GenericResult )然后标记狭窄的 getJellyBeanReport() 方法as @Deprecated 阻止新来的人使用它?

        4
  •  0
  •   noah    16 年前

    public JellyBeanResult getJellyBeanReport() {
        return getJellyBeanReport(JellyBeanResult.class);
    }
    
    public <T extends JellBeanResult> getJellyBeanReport(Class<T> resultType) {
        // get the correct report type
    }
    
        5
  •  0
  •   Rob Spieldenner    16 年前

    可能性:

    • 如果您只想重用该功能,那么可以让所有其他类(如ChocolateBarResult)使用JellyBeanResult,而不是扩展它。记住,组合往往比继承更好。
    • 保留API的当前版本,以便现有用户可以使用。创建一个新版本,它将包含您所做的更改,这样,如果用户需要新功能,他们就需要升级他们的代码库。如果您这样做了,那么就创建某种变更指南,并可能在一两个发布周期内弃用该方法以允许变更。
        6
  •  0
  •   richj    16 年前

    假设您还没有发布当前版本的API,您能否重构以使用通用接口和协变返回类型?

    public interface ConfectionaryResult {...}
    public class ChocolateBarResult implements ConfectionaryResult {...}
    public class JellyBeanResult implements ConfectionaryResult {...}
    
    public interface ConfectionaryInventory {
        ConfectionaryResult getReport();
    }
    
    public class JellyBeanInventory implements ConfectionaryInventory {
        JellyBeanResult getReport() {...}
    
        @deprecated "Use JellyBeanInventory.getReport() instead"
        JellyBeanResult getJellyBeanReport() {
            return getReport();
        }
    }
    
    public class ChocolateBarInventory implements ConfectionaryInventory {
        ChocolateBarResult getReport() {...}
    }
    

        7
  •  0
  •   user280592    16 年前