Roman
Roman

Reputation: 66196

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

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?

Upvotes: 0

Views: 104

Answers (2)

sanbhat
sanbhat

Reputation: 17622

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) {

Upvotes: 2

ssantos
ssantos

Reputation: 16536

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?

Upvotes: 0

Related Questions