java - 惯用的 Java : constraining data

标签 java coding-style

玩转简单的 Java Point我想将 X 和 Y 值限制为 double 值,并且必须在 -10 到 10 范围内(包括 -10 和 10)。我已经编写了一些代码,但距我编写 java 已经很多年了,我想知道现代 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 + "]"); 
    }
}

最佳答案

我可能会这样做:

public class Point
{

    private static final double X_MIN = -10.0, X_MAX = 10.0;
    private static final double Y_MIN = -10.0, Y_MAX = 10.0;

    private double x, y;

    public Point(double x, double y) throws IllegalArgumentException
    {
        setX(x);
        setY(y);
    }

    public double getX()
    {
        return x;
    }

    public double getY()
    {
        return y;
    }

    public void setX(double x) throws IllegalArgumentException
    {
        if (x < X_MIN || x > X_MAX)
        {
            throw new IllegalArgumentException("X out of range.");
        }

        this.x = x;
    }

    public void setY(double y) throws IllegalArgumentException
    {
        if (y < Y_MIN || y > Y_MIN)
        {
            throw new IllegalArgumentException("Y out of range");
        }

        this.y = y;
    }

    @Override
    public String toString()
    {
        return String.format("[%.1f,%.1f]", x, y);
    }
}

关于java - 惯用的 Java : constraining data,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27890776/

相关文章:

c++ - 代码风格 : Reuse of a control expression or control variable in the branch of a switch/if statement

与库交互时的代码风格 (C)

java - 将 Eclipse Java 项目转换为 Google AppEngine 项目

java - Spring Amqp 在 springframework RetryCallback 类中有 NoClassDefFoundError

java - 如何为多种事件类型存储监听器

java - 部署规则集所需的 Java 版本不可用

java - 如何打印斐波那契数列,多线程?

javascript - 在 JavaScript 中定义属性和命名约定

java - 缺少 android 权限时适合抛出什么异常?

programming-languages - 您重构代码的频率和频率如何?