首先请看如下的代码。
class Help {
private int n;
Help() {
this.n = 0;
}
public void setMe(int n) {
Helper.setValue(this, n);
}
public void setN(int n) {
this.n = n;
}
}
class Helper {
static public void setValue(Help h, int n) {
h.setN(n);
}
}
public class TestQuestion{
public static void main(String[] args) {
Help h = new Help();
h.setMe(13);
}
}
Help的setMe方法调用了Helper的setValue方法,Helper的setValue方法又调用了Help的setN方法。这样似乎中间的Helper没有用。但是它可以加一些检测操作,使得这种检测操作分离出来。具体如下:
class Help {
private int n;
Help() {
this.n = 0;
}
public void setMe(int n) {
Helper.setValue(this, n);
}
public void setN(int n) {
this.n = n;
}
}
class Helper {
static public void setValue(Help h, int n) {
if (n < 1000) {
h.setN(n);
} else {
System.out.println("The value is beyond 1000.");
}
}
}
public class TestQuestion{
public static void main(String[] args) {
Help h = new Help();
h.setMe(13);
}
}
这样可以把检测分离出来,符合软件工程团队开发的的思想。