I have a class with code like the following, where I want it to be trivial to use any class/type which represents a number. I find myself defining a large amount of methods, like the following:
public class Range {
private BigDecimal inferior = new BigDecimal(0);
private BigDecimal superior = new BigDecimal(1);
public Range(BigDecimal inferior, BigDecimal superior) {
if (inferior.compareTo(superior) == -1) {
this.inferior = inferior;
this.superior = superior;
}
}
public Range(int inferior, int superior) {
this(new BigDecimal(inferior), new BigDecimal(superior));
}
public Range(Integer inferior, Integer superior) {
this(new BigDecimal(inferior), new BigDecimal(superior));
}
public Range(float inferior, float superior) {
this(new BigDecimal(inferior), new BigDecimal(superior));
}
public Range(double inferior, double superior) {
this(new BigDecimal(inferior), new BigDecimal(superior));
}
}
I haven't even written every combination possible! For instance, one which takes a float and a double, or an int and a BigDecimal.
How could this be achieved in a clean way, so that there are parameters valid for multiple classes/data types which are already predefined, or even primitives? I've considered adapters and proxies, but I regularly find myself not understanding the explanations and I can't figure out if they fit my use case and if so how - this question may have already been answered on SO, but if so at least I would like to see if anyone can explain it to me according to this particular example.