I have the same method in 2 classes that copy fields from one object to builders. I want to refactor it but I do not know if I should create a static method in an utility class or abstract it to a superclass.
The classes that shares this code are Beans and part of a multithreading app.
The method would be like:
protected static void copyPartyGroup(Message.Builder msgBuilder,
final PartyGroup partyIDsGroup, Party.Builder rartyBuilder) {
rartyBuilder.setPartyID(partyIDsGroup.getId())
....
msgBuilder.setID(partyIDsGroup.getId())
....
}
Thank you very much for your help.
You can also use a trait in java 8, It's an interface with default methods
see : https://opencredo.com/traits-java-8-default-methods/
or : https://dzone.com/articles/using-traits-in-java-8
If your two classes not share a same parent structure, don't use a super abstract class, if the only reason to create this super class is to share your method copyPartyGroup
is not a good practice.
see : Liskov substitution principle
If you want to respect the Single Responsability Principle:
I think you have to create a service class.
In your case, maybe a threadsafe singleton with syncronized methods for rartyBuilder.setPartyID
and msgBuilder.setID
. (see Initialization-on-demand holder idiom)