Reputation: 5660
I have seen so many codes of the following type:
private final Map<String, String> map;
public SomeConstructor() {
this.map = new HashMap<String, String>();
}
Well such codes can easily be replaced by passing in map as a parameter to SomeConstructor. Extending my questions, are there some cases where dependency injection is NOT the right thing to do instead using constructor to initialize ?
Upvotes: 2
Views: 66
Reputation: 6969
Think of a unit test.
SomeClass c = new SomeClass(new HashMap(), new HashMap(),
new HashMap(), new ArrayList());
is quite a bit more annoying than
SomeClass c = new SomeClass();
If you can't foresee anyone supplying a different implementation, ever, there's really no point.
Consider
SomeClass {
List list = new ArrayList();
}
If you inject that, one could pass a LinkedList
instead, which I guess is a win - no other code is modified. But how likely is it that implementation of SomeClass
won't change as a result?
In short, I'd say
Upvotes: 3
Reputation: 57162
Use dependency injection if you might want to inject in different types of parameters, and it's not just an internal detail. In simple cases like this, another class probably isn't going to want to inject the type of map - that's an internal detail. But, for something like a database service, you would want to inject in different types (and stubs for testing).
Upvotes: 4