superclass vs utility class for common code

1.6k Views Asked by At

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.

2

There are 2 best solutions below

1
On BEST ANSWER

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

enter image description here

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)

enter image description here

0
On

If you can extract a static method, then it is better to just do that.

Using inheritance to share code couples your code and makes it really hard to untangle later.