jeudi 27 février 2020

Overusing dependency injection and factory pattern

I am working in an android project which have factory class polluted with too many object creation. Basically, we have more than 10 classes in our application and initialise all objects inside a single factory class. This will be used by any class in an application to access required object. Eg: factory.getObjectX. Currently, this factory holds 12 member variable objects and it is creating ~18 objects. So, it kills readability. This class would grow further in the future and it is already bloated up.

Another issue is that we are using dependency injection. So, this factory creates all required objects of classA and then initialise classA which explains ~18 object creation and 12 member variables I mentioned above. I don't think we need dependency injection here because objects required for classA are within the scope of it and also, not used by any other class in the application. When I want to create new object in classA tomorrow, then factory class and classA would be disturbed which violates SRP and open closed principle.

Two questions,
1.I am more interested in dependency injection(2nd) problem. Do I need dependency injection in this situation? When should I use dependency injection generally? My understanding is that if a same object is required in multiple classes then it can be injected.Also, if a class have to act upon different variants of an object then it can be created outside and injected.

2.I am open to solve first problem(single factory with all object creation) also.

Please share your thoughts and suggestions.

Aucun commentaire:

Enregistrer un commentaire