HiveBrain v1.2.0
Get Started
← Back to all entries
patternjavaMinor

Constraining data in idiomatic Java

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
constrainingdataidiomaticjava

Problem

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 ) {
            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 + "]"); 
    }
}

Solution

Remove the magic numbers for the constrained values and give them constants instead:

private static final double MAX_VAL = 10;
private static final double MIN_VAL = -10;


These constants should also be printed in the exception statement instead of hard-coding the values. Otherwise, if you just change the constants, the code will give inaccurate results.

Regarding the class name, consider renaming it to something like Constrained2DPoint. Points can also have a 'z' if they're used in 3D space, so the name Point may be ambiguous in either case.

Code Snippets

private static final double MAX_VAL = 10;
private static final double MIN_VAL = -10;

Context

StackExchange Code Review Q#77259, answer score: 5

Revisions (0)

No revisions yet.