There is a code snippet presented in The Pragmatic Programmer on page 143 as:
public class Colada {
private Blender myBlender;
private Vector myStuff;
public Colada() {
myBlender = new Blender();
myStuff = new Vector();
}
private doSomething() {
myBlender.addIngredients(myStuff.elements());
}
}
This obeys the Law of Demeter / Principle of Least Knowledge.
Is it preferable to, and are there any caveats for, replacing it with the following, which utilises Dependency Injection?
public class Colada throws IllegalArgumentException {
private Blender myBlender;
private Vector myStuff;
public Colada(Blender blender, Vector stuff) {
if (null == blender) {
throw new IllegalArgumentException()
} else {
myBlender = blender;
}
if (null == stuff) {
throw new IllegalArgumentException()
} else {
myStuff = stuff;
}
}
public static Colada createDefaultInstance() {
Blender blender = new Blender();
Vector stuff = new Vector();
return new Colada(blender, stuff);
}
private doSomething() {
myBlender.addIngredients(myStuff.elements());
}
}