Skip to content
Advertisement

Composition or Inheritance for classes with almost similar implementations but different input and outputs for methods?

I have the following classes, which have quite similar method implementations. Only the classes’ method inputs and outputs seem to be of different types. When I put it like this, it sounds like a case for inheritance, however, the fact that the inputs and outputs are different and are related to two lambdas, make me wonder if they should remain without any relationship, as one lambda cannot be thought of in place of another (To be a case for inheritance).

My first class looks like the following.

JavaScript

My second class looks like the following.

JavaScript

As you can see, the methods perform almost the same actions. Only the indexCreatedEmployee and indexCreatedJob methods from the classes have an extra step of processing the input.

Should I keep these classes as they are now without any relationships between them, or should I create an abstract persistence manager class and perform the following.

Move createIndexIfNotExists to the abstract class Create abstract methods search(), invokeLambda() and indexCreatedData() methods and implement them in each child class. The data types MyJobInput and MyEmployeeInput are POJO classes that don’t have any relationship. So I guess these methods I mentioned would then take “Object” parameters? EmployeeLambda and JobLambda are again classes with no relationship between them. Another concern I had towards creating some sort of inheritance was that, Employee Lambda and JobLambda cannot be used inter-changeably. So was wondering if they should inherit the same parent class just because they’re both lambda classes.

OR is there another way to go about this? Any advice would be much appreciated. Thank you very much in advance.

Advertisement

Answer

As promised yesterday, here is what I would do.

Create a Lambda interface and make JobLambda and EmployeeLambda implement it

JavaScript

Do the same for DataPersistence

JavaScript

Then create a parent class PersistenceManager which contains all the duplicated methods, parametrized for the type of input/output:

(Note: I didn’t complete everything, but I did something just to make you understand the concept)

JavaScript

At this point, you can specialize your classes by simply choosing the parameters

… all the rest of the code will be shared in the parent class.

JavaScript

… and use them like this:

JavaScript
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement