This question is related to the one here: configurable dependencies with easy to mock out default implementations.
My goal is to design small library, following DI pattern. Having code like the following is this right usage of DI?
ValuesConfiguration is just wrapper for Map. It is kind of Value Object, it is created by client in runtime, so there is no possibility to use dependency injection. Previous version (in related question) had this configuration as a constructor argument, but it seemed not to be “real” dependency.
public class Parser {
private ValuesConfiguration configuration;
private ValuesProvider valuesProvider;
private ValuesMapper valuesMapper;
public Parser() {}
public Result parse(String parameterName) {
initDefaults();
List<Values> values = valuesProvider.getValues(parameterName);
...
return valuesMapper.transformValues(values, configuration);
}
private void initDefaults() {
if(valuesProvider == null) {
valuesProvider = DefaultsFactory.getDefaultValuesProvider();
}
}
public void setConfiguration(ValuesConfiguration configuration) {
this.valuesConfiguration = configuration;
}
public void setValuesProvider(ValuesProvider provider) {
this.valuesProvider = provider;
}
...
}
Isn’t it better to put configuration as a parse() method additional parameter?
An alternative to Dependency Injection is for a component to discover its own dependencies. It appears to me that you have used the later model.
If you had used dependency injection you would only pass the values its needed and no more. i.e. all its dependencies are injected not extracted. The component wouldn’t need to know where the values came from.
A big hint is that your constructor takes no values and your setters are passed generic objects which are not needed once the component has been properly initialised.
How you could change it to use DI.