> <
Category: Technicals


In this article I'll try to showcase how factory pattern can help us to loosen our code dependency to achieve a better structured/designed software.
As you probably know dependency injection can help us to develop better software which has more separation of concerns and many more benefits
that comes with it.

All that aside back to the main topic, what has factory pattern got to do with it?


Lets assum that we have class A thats depended on class B, typicaly we declare our depenedency on interface parrent of B so that our code is not
depended on a concrete implementation and we inject the B class as the implenetation while/after instantiation of an object of type A, in this way
we have loosen our dependency.
But what if our A class needs to instantiate unknown number of objects of type B at a somepoint?


Here factory pattern comes to work, in class A we declare our dependency to factory interface of type B's parent interface which helps us to generate as many obejct of type B as we want and whenever we want.


Lets say we are developing a weather app that uses multiple service provider to get the average predicted temperature of a day.
I know that it's not a perfect example but our objective it to see how we can use it, not when to use it.

So we have these classes/inferfaces:

So far so good, in our weather app we've declared our dependency to WeatherServiceCaller and we can use any of it's implementation.
For getTemperature method dependency injection works perfectly but its not the case for getAverageTemperature as you can see at line 17 of WeatherApp class.
To resolve this problem we can pass the callers to the function alongside the providers or generate callers at provider class so we can use getter method to access it, although I'm not sure if its a good practice or not.

In our case we try to solve it by injecting a caller factory.

Now if you look at line 21 of BetterWeatherApp class you will see that we've resolved our problem, I know that this example has many problem and even the implementation is not good but I hope you see my point which is how we can use the factory pattern to loosen some dependencies of our code.

Why bother so much?

I'm not gonna get into benefits of DI in developing better software, yet we know there is no such thing as perfect software, we only can implement softwares in a way that its easier to improve it and that means we have to keep changing our code to make it better and in doing so we need to have have really good test suite so we know which change is breaking the intended functionality of the code, by DI we make our code more testable.

in our example case we saw that original WeatherApp class was tightly coupled with the HttpWeatherServiceCaller which makes it hard to write independent test for, and the BetterWeatherApp class we can easily mock the factory class and write tests for our codes.


Let me know your thoughts on the matter.