I wrote a simple class to demonstrate a chain style method design:
public class Cal {
private Cal(){}
private boolean isCheckArguments = false;
public static Cal useAbs() {
return new Cal(){
@Override int check(int i) {
return Math.abs(i);
}};
}
public static Cal useNormal() {
return new Cal();
}
public Cal checkArguments() {
isCheckArguments =true;
return this;
}
int check(int i){ return i;}
public int plus(int i, int j) {
if(isCheckArguments && i<j){
throw new IllegalArgumentException("i<j!");
}
return check(i+j);
}
}
So the client code can be:
Cal cal = Cal.useAbs().checkArguments();
int sum = cal.plus(100,2);//IllegalArgumentException occurs
Cal cal2 = Cal.useAbs();
int sum2 = cal.plus(-100,2);//98
Cal cal3 = Cal.useNormal();
int sum3 = cal.plus(-100,2);//-98
My question is: Is it a reasonable design? comparing to: int plus(int a, int b, boolean useAbs, boolean checkArguments)
. Thanks!