Exercise 26 of The Pragmatic Programmer
Posted
by _ande_turner_
on Stack Overflow
See other posts from Stack Overflow
or by _ande_turner_
Published on 2010-03-19T07:22:51Z
Indexed on
2010/03/19
7:41 UTC
Read the original article
Hit count: 498
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) {
blender == null ? throw new IllegalArgumentException() : myBlender = blender;
stuff == null ? throw new IllegalArgumentException() : myStuff = stuff;
}
public getInstance() {
Blender blender = new Blender();
Vector stuff = new Vector();
return new Colada(blender, stuff);
}
private doSomething() {
myBlender.addIngredients(myStuff.elements());
}
}
© Stack Overflow or respective owner