Sometimes when I design my classes, I need some dependency classes with similar constructor parameters. Assume we have
interface IDependency {
void DoSomething();
}
class DependencyClass : IDependency {
public DependencyClass(int length) {...}
...
}
class MainClass {
public MainClass(int length, IDependency dependency) {...}
...
}
MainClass
needs an instance of DependencyClass
with the same length
. I have two methods in mind to deal with it:
Not creating instances of MainClass
directly and always getting them from a factory. This way I can make sure that the desired IDependency
instance will be provided to MainClass
constructor.
Passing a factory interface, say IDependencyFactory
, to MainClass
constructor instead of IDependency
. So that I can get the desired instance of DependencyClass
within my MainClass
implementation.
I'm not sure if either of them is a good choice. Is there a best practice in this case?
This is a very interesting question and the answer lies in what you try to achieve here.
Solution 1. you provided will make your IDependency
the main factory interface, all instanced will be implemented with IDependency
interface which will provide you with a lot of scalability - you will be able to use the IDependency
interface to initialize additional classes in the future with different functionality, which is the classic use and implementation of factory design pattern.
solution 2. you provided will make your MainClass
well, the Main Class of the program, you will handle the instances and their behavior inside the main class and the advantage here is that you can manage all of your instances through IDependency
, and the only thing you do in MainClass
is handle their logic, MinaClass
will be your instances transporter and all of the fundamental changes for the base classes will be made in the interface IDependency
which is a classic solution for Dependency Inversion.
The question still remains, what you are trying to achieve. Consider this question and the two possibilities and you have your answer.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With