说我有一些课Foo
class Foo {
protected String x = "x";
public String getX() {
return x;
}
}
Run Code Online (Sandbox Code Playgroud)
我有一个使用Foo并违反LoD的程序
class Bar {
protected Foo foo;
public Bar() {
this.foo = new Foo();
}
public Foo getFoo() {
return foo;
}
}
public static void main(String [] args) {
Bar bar = new Bar();
String x = bar.getFoo().getX();
}
Run Code Online (Sandbox Code Playgroud)
重构使用LoD看起来像这样:
class Bar {
protected Foo foo;
public Bar() {
this.foo = new Foo()
}
public String getFooX {
return foo.getX();
}
} …Run Code Online (Sandbox Code Playgroud) java refactoring intellij-idea law-of-demeter automated-refactoring