Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Injecting a dependency having constructor parameters in common with the higher level class

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:

  1. 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.

  2. 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?

like image 895
Persian Astroman Avatar asked Aug 13 '18 07:08

Persian Astroman


1 Answers

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.

like image 199
Barr J Avatar answered Oct 13 '22 12:10

Barr J