The code that I write ( MyService ) includes the ability of each client to connect its own calculator at a certain point in processing. This will set up business rules. The moment the calculation is done, we know many things, some of which may be related to the calculation. MyService will be created for a specific set of input parameters and will be launched once.
My plan is to use dependency injection to give MyService a calculator in the constructor. This allows various users to connect their own calculator . calculator returns the amount representing the premium for this particular MyService mileage. Others will implement various calculators, and I will need to update my code without breaking them. i.e. keep compatibility backwards.
The problem is that different calculator implementations will require different parameters. These parameters cannot be entered by the constructor in the calculator at the time of creation of MyService , because they are not known, any processing in MyService occurs.
The calculator will be called only once within a specific instance of MyService . Therefore, on the one hand, all parameters can be passed in the constructor, and there is a method without parameters that returns a response. On the other hand, all parameters are passed in a method call.
AlwaysZeroCalculator can simply return 0 , so no parameters are required. PercentageCalculator requires amount to apply percentage. For even more complex amount and customerNumber required. We can assume that no matter what the calculator may be needed for, it is known at runtime of MyService (or it can itself be introduced into the calculator implementation as a sleep session).
How to implement this?
Here are a few options and problems:
- Make all calculators implement an interface that includes all parameters as arguments to the method. But, if something superfluous is added, they should all change, which will inevitably turn this into the second option.
- Make different interfaces (
ICalculator , ICalculatorWithAmount , ICalculatorWithAmountAndCustomerNumber , etc.). MyService will need to see which calculator interface it implements, passes it to this interface, and then calls the corresponding calculate(..) method. - Enter a parameter object that includes everything they need. This means that even the simplest
calculator depends on everything. - Make different interfaces and different versions of
MyService that expect one of these interfaces. - Add a
calculatorFactory instead of a calculator . factory will use all possible parameters and create a calculator with only the correct ones. It seems that this simply transfers the problem to another place without solving it. - Spend some awful hash file with calculator and enter security, dependency declaration will be damned
Is there a better way?
source share