mardi 29 septembre 2020

I've been researching on when to use factory pattern and when dependency injection and some of the answers don't make sense to me

I've been working on a legacy system and we want to cut the cord and modernize everything. For that purpose I have started researching patterns that solve some of the problems we had in the old system. There are plenty of threads here on the topic of factory pattern vs dependency injection but the answer don't always make sense to me.

Answers tend to either suggest that DI is more modern or flexible or that factory pattern still has its place, it is just used for different situations. Or even that both aren't mutually exclusive and can be implemented at the same time. Either way DI is usally made out to be more flexible. If you want to make changes you have more work to do with the factory pattern. I guess that depends on the kind of change you want to make, but to the typical scenarios I can think of it is the opposite.

Assume I'm looking for a solution for making phone calls. We might test different telephone systems and within those telephone systems different APIs. Now let's say phone functionality is integrated in several different projects and modules. If we want to switch to a different API or a new phone system with DI we have to find each project that uses the phone interface and instantiate it with a different object. So I have to find all the projects that use the interface and change at least one line code in each. If I use a factory however I can just change the Method that gets me an instance to get me an instance of the new class. One line for every single project.

In short, with DI each project would have to be updated every time a new interface is to be used but with a factory only one method needs to change. Moreover, if i want a different instance for a specific project I could just use an optional parameter. Like "GetPhoneApi("StarfaceTest")"

I never see this cited as an advantage in all the discussions, which makes me wonder if I am missing something? What exactly makes DI more flexible then?

Aucun commentaire:

Enregistrer un commentaire