0

I have to make a layer that pulls in data from three different sources based on some setting as we are trying to migrate to new systems and we still want to maintain legacy flow till we switch.

Lets say that we need to get a consolidate POJO which contains secondary heavy POJOs.

class X { 
   Y1 obj1;
   Y2 obj2;
   Y2 obj3;
...
}

I have made a layer which can call the either of the downstream service and brings in the data. How i would like to have is that each of Y1 and Y2 and Y3 have their own populators and they could be built from the different types of POJO from different services that this layer is calling. Is there an elegant way to do this so that later on, I only have to do code addition. Also, I would like to adhere as much as possible to SOLID principles.

One way i thought of is to have a strategy pattern for each type of Y's and we select the strategy to transform based on the service and its pojo passed.

But this leads to class boom for each new complex Y inside X, I will have to write multiple strategies which is basically a lot of classes for a simple thing.

Mukul Anand
  • 606
  • 6
  • 24

1 Answers1

0

Use Dependency Injection. So, for your class, have the constructor be given the obj1, obj2 and obj3, to to use, rather than have it create those objects itself:

class X { 
   private final Y1 obj1;
   private final Y2 obj2;
   private final Y2 obj3;

   X(Y1 obj1, Y2 obj2, Y2 obj3)
   {
      this.obj1 = obj1;
      this.obj2 = obj2;
      this.obj3 = obj3;
   }
...
}

This works better if Y1 and Y2 are interfaces or abstract base classes.

Raedwald
  • 46,613
  • 43
  • 151
  • 237
  • I wasnt looking for how to inject the prepared values of any class Yi object inside X. Rather, how to make each Yi being populated from the a of POJO that I am getting back after calling a service.(i can call multiple services for for relevant data) and so i need to have multiple strategies for each Yi to prepare it from that upstream service that I called. – Mukul Anand Feb 20 '19 at 08:29