Playing with a simple Java Point
class where I would like to constrain the X and Y values to be doubles that must be in the range -10 to 10, inclusive. I've written some code, but it's been years since I've written java and I would like to know if this is how it would be written in modern Java:
public class Point {
private double x;
private double y;
public Point(double x, double y) {
constrain("x", x);
constrain("y", y);
this.x = x;
this.y = y;
}
// is there a cleaner/shorter way of handling this, such as a direct way of declaring a
// subtype of double that I could use in method signatures?
protected static void constrain(String name, double val) {
if ( val < -10 || val > 10 ) {
throw new IllegalArgumentException(name + " must be between -10 and 10");
}
}
public double getX() { return x; }
public void setX(double x) {
constrain("x", x);
this.x = x;
}
public double getY() { return y; }
public void setY(double y) {
constrain("y", y);
this.y = y;
}
@Override
public String toString() {
return ("[" + x + "," + y + "]");
}
}