Is it possible to refactor these methods to avoid code duplication?

109 Views Asked by At

I have a bunch of utility-like methods, which looks very similar, like:

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);
}

Classes EventAttorneyModel and CaseAttorneyModel are JPA entities and do not have common predecessors except for the Object class.

I wonder if there's a way I can get rid of duplicating the code, as there will be many such methods in future?

2

There are 2 best solutions below

0
On

It looks like you could create a generic class encapsulating both methods.

And you could make it a singleton class following the idea of the post below.-

how to create a generic singleton class in java?

8
On

I think best way would be to create an interface

interface AttorneyModel{

   public void setSequence(Long l);

}

and make 2 classes implement them, and have method signature like

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