Dependency injection OR configuration object?
I have the following constructor for my Class
public MyClass(File f1, File f2, File f3, Class1 c1, Class2 c2, Class3 c3)
{
..........
}
As can be seen, it has 6 parameters. On seeing this code, one of my seniors said that instead of passing 6 parameters I should rather pass a configuration object.
I wrote the code this way because recently I have read about "Dependency injection", which says "classes must ask for what they want". So I think that passing a configuration object will be against the principle.
Is my interpretation of "Dependency injection" corr开发者_C百科ect? OR Should I take my senior's advice?
"Configuration object" is an obtuse term to apply in this situation; it frames your efforts in a purely mechanical sense. The goal is to communicate your intent to the class's consumer; let's refactor toward that.
Methods or constructors with numerous parameters indicate a loose relationship between them. The consumer generally has to make more inferences to understand the API. What is special about these 3 files together with these 3 classes? That is the information not being communicated.
This is an opportunity to create a more meaningful and intention-revealing interface by extracting an explicit concept from an implicit one. For example, if the 3 files are related because of a user, a UserFileSet
parameter would clearly express that. Perhaps f1
is related to c1
, f2
to c2
, and f3
to c3
. Declaring those associations as independent classes would halve the parameter count and increase the amount of information that can be derived from your API.
Ultimately, the refactoring will be highly dependent on your problem domain. Don't assume you should create a single object to fulfill a parameter list; try to refactor along the contours of the relationships between the parameters. This will always yield code which reflects the problem it solves more than the language used to solve it.
I don't think using a configuration object contradicts using dependency injection pattern. It is more about the form in which you inject your dependencies and a general question of whether it's better to have a function (in this case the constructor) that takes 20 parameters or combine those parameters into a class so that they are bundled together.
You are still free to use dependency injection, i.e. construct the configuration object by some factory or a container and inject it into the constructor when creating an instance of your class. Whether or not that's a good idea also depends on the particular case, there are no silver bullets ;)
精彩评论