I have a factory class that currently takes 6 params in it's constructor, and I just hit a need to add another.
Normally, this would scream to me "Hey, your class has too many dependencies, therefore, it does too much!"
However, given this class is strictly a factory, is that really the case? Should I be concerned about the growing number of dependencies? If so, what strategies should I consider for refactoring this?
Update:
I had considered the builder pattern, but for a factory, isn't that overkill?
(Ie., WidgetFactoryBuilder
, which builds a factory which builds widgets.).
Additionally, I don't understand how a builder really alleviates my dependencies - it just moves them from the constructor to methods -- which seems to obfuscate things more -- however this could be down to a poor understanding of how to apply the builder pattern in this situation.
If the number of parameters can vary, then use a variable arity ("varargs") parameter. Declare an array instead of all those other instance variables. The variable arity parameter is typed as an array when in the method. Your subclass constructors will not have to change at all.
This method has four parameters: the loan amount, the interest rate, the future value and the number of periods.
Example of parameterized constructor In this example, we have created the constructor of Student class that have two parameters. We can have any number of parameters in the constructor. //Java Program to demonstrate the use of the parameterized constructor.
First of all, I should mention that I don't necessarily think six parameters are too many. But if you insist...
I don't think the problem at all lies in the number of parameters to the constructor.
The builder pattern that others recommend is useful for classes that contain a lot of state. This is rarely the case for a factory. I am instead going to assume that the parameters you are talking about are dependencies on other classes. The real problem is that your factory has too many dependencies - not that its constructor takes too many arguments.
Instead you need to look at design. Why does the factory have so many dependencies? Is it possible to reduce that number somehow? Maybe the objects that the factory creates are themselves too complex?
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