【问题标题】:How to set class invariants without using conditional if statements如何在不使用条件 if 语句的情况下设置类不变量
【发布时间】:2015-02-08 02:28:50
【问题描述】:

我有一个叫做像素的类。我正在制作一个构造函数,它接收单个像素的红色、绿色、蓝色、alpha 值。我怎样才能让程序只接受这些的有效值(例如 0 到 255)而不使用 if 语句? 下面是我的课:

public class Pixel {
    public int redPix;
    public int bluePix;
    public int greenPix;
    public int alpha;

    public Pixel(int redPix , int bluePix , int greenPix , int alpha) {
        this.redPix = redPix;
        this.bluePix = bluePix;
        this.greenPix = greenPix;
        this.alpha = alpha;
    }


    public void setRed(int redPix) {
        this.redPix = redPix;
    }
    public int getRed() {
        return(redPix);
    }

    public void setBlue(int bluePix) {
        this.bluePix = bluePix;
    }

    public int getBlue() {
        return(bluePix);
    }

    public void setGreen(int greenPix) {
        this.greenPix = greenPix;
    }

    public int getGreen() {
        return(greenPix);
    }

    public void setAlpha(int alpha) {
        this.alpha = alpha;
    }

    public int getAlpha() {
        return(alpha);
    }

    public static void main(String[] args){
    }


}

【问题讨论】:

  • 为什么不使用条件语句?
  • 你需要做一些事情如果给定的值在0..255区间内。这是一个条件。您可以使用三元运算符,但这本质上是 if 语句的较短版本。我真的不明白为什么避免ifs 会有好处。
  • 我也想知道您为什么要避免使用条件,但是您是否使用注释进行了调查?可能有一些现有的验证注释库,或者您可以编写自己的...
  • 抱歉,我在某种程度上误导了这个问题。我一直在寻找不使用 if 语句的捷径。基本上,我想知道 java 是否有一些我可以导入的东西可以为我检查我的论点。理论上我可以使用 if 语句,但我希望我的代码也易于阅读。
  • @Quinty,assert 语句会执行此操作,并且在您的情况下是推荐的做法。

标签: java pixel data-manipulation


【解决方案1】:

您可以使用断言来指定类不变量。实际上推荐用于私有方法。

assert x >= 0 && x <= 255;

【讨论】:

  • 谢谢!这在我的教科书中没有提到,但我也会尝试使用它!
  • 请阅读这些关于断言的 Oracle 约定:docs.oracle.com/cd/E19683-01/806-7930/assert-13/index.html
  • 也可以说AssertionError(由assert产生)在发生不应该发生的事情时使用。但是,如果客户可以访问您的代码,那么您应该使用具有适当抽象的异常(如IllegalArgumentException)。
【解决方案2】:

你能做的最好的办法就是像这样编写方法助手:

private void checkArg(int arg) {
        if (arg < 0 || arg > 255) {
            throw new IllegalArgumentException("Wrong argument: " + arg);
        }
    }

然后在所有方法的开头使用它。

【讨论】:

  • 谢谢!我将尝试两个答案!
猜你喜欢
  • 1970-01-01
  • 2018-12-15
  • 2012-05-22
  • 1970-01-01
  • 2017-10-14
  • 2021-09-22
  • 1970-01-01
  • 2021-09-29
  • 1970-01-01
相关资源
最近更新 更多