次のクラスを仮定します。
interface Thing {
void doSomething();
}
public class Test {
public void doWork() {
//Do smart things here
...
doSomethingToThing(index);
// calls to doSomethingToThing might happen in various places across the class.
}
private Thing getThing(int index) {
//find the correct thing
...
return new ThingImpl();
}
private void doSomethingToThing(int index) {
getThing(index).doSomething();
}
}
Intelli-J は、DoSomethingToThing が関数の結果を使用しており、おそらくフィールド、パラメーター、またはオブジェクト自体のメソッドしか呼び出せないため、デメテルの法則に違反していると言っています。
私は本当にこのようなことをしなければなりませんか:
public class Test {
//Previous methods
...
private void doSomething(Thing thing) {
thing.doSomething();
}
private void doSomethingToThing(int index) {
doSomething(getThing(index));
}
}
私はそれが面倒だと思います。デメテルの法則は、あるクラスが別のクラスの内部を知らないがgetThing()
、同じクラスであるようにするためのものだと思います!
これは本当にデメテルの法則に違反していますか?これは本当にデザインを改善していますか?
ありがとうございました。