是否有可能重构这些方法以避免代码重复?

时间:2013-09-12 17:41:15

标签: java jpa refactoring code-duplication

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

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类之外没有共同的前任。

我想知道是否有办法摆脱重复代码,因为将来会有很多这样的方法?

2 个答案:

答案 0 :(得分:2)

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

interface AttorneyModel{

   public void setSequence(Long l);

}

并使2个类实现它们,并具有类似

的方法签名
public static <T extends AttorneyModel> void addLeadingAttorney(T newAttorney,
                                List<T> existingAttorneys) {

答案 1 :(得分:0)

看起来你可以创建一个封装两种方法的generic class

你可以按照下面这篇文章的想法把它变成一个单身课.-

how to create a generic singleton class in java?

相关问题