【问题标题】:Is it possible to refactor these methods to avoid code duplication?是否可以重构这些方法以避免代码重复?
【发布时间】:2013-09-17 05:34:04
【问题描述】:

我有一堆类似实用程序的方法,看起来非常相似,比如:

public static void addLeadingAttorney(EventAttorneyModel newAttorney,
                                List<EventAttorneyModel> existingAttorneys) {
    for (EventAttorneyModel existingAttorney : existingAttorneys) {
        existingAttorney.setSequence(existingAttorney.getSequence() + 1);
    }
    newAttorney.setSequence(1L);
    existingAttorneys.add(0, newAttorney);
}


public static void addLeadingAttorney(CaseAttorneyModel newAttorney,
                                List<CaseAttorneyModel> existingAttorneys) {
    for (CaseAttorneyModel existingAttorney : existingAttorneys) {
        existingAttorney.setSequence(existingAttorney.getSequence() + 1);
    }
    newAttorney.setSequence(1L);
    existingAttorneys.add(0, newAttorney);
}

EventAttorneyModelCaseAttorneyModel 类是 JPA 实体,除了 Object 类之外没有共同的前身。

不知道有没有什么方法可以避免重复代码,因为以后会有很多这样的方法?

【问题讨论】:

  • 它们没有共同的父级或接口是否有原因?
  • 如果两个类都实现了相同的接口,这将很容易做到。

标签: java jpa refactoring code-duplication


【解决方案1】:

我认为最好的方法是创建一个界面

interface AttorneyModel{

   public void setSequence(Long l);

}

并让 2 个类实现它们,并具有类似的方法签名

public static <T extends AttorneyModel> void addLeadingAttorney(T newAttorney,
                                List<T> existingAttorneys) {

【讨论】:

  • 这就是要走的路,imo。并对所有其他类集重复此操作。
  • 不需要泛型。只需使用 AttorneyModel 作为类型。
  • 我会去的。我唯一关心的是如果我添加该接口,JPA 将如何反应?
  • @RobertHarvey 无法将List&lt;CaseAttorneyModel&gt; 传递给List&lt;AttorneyModel&gt;
  • @RobertHarvey:在这种情况下,首席律师应该具有相同类型的约束将丢失。
【解决方案2】:

看起来您可以创建一个 generic class 封装这两种方法。

您可以按照下面帖子的想法将其设为单例类。-

how to create a generic singleton class in java?

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-09-28
    • 1970-01-01
    • 1970-01-01
    • 2021-08-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-06-28
    相关资源
    最近更新 更多