如何测试对象是否是重载版本?

时间:2015-10-14 18:54:47

标签: java

我有2个构造函数,主要区别在于BigDecimal bulkPriceint bulkQuantity的存在。我正在尝试编写一种方法来测试该项目是否具有批量选项,以便我可以正确计算总价。关于如何编写isBulk方法,我有点迷失......

public Item(final String theName, final BigDecimal thePrice) {

    myName = Objects.requireNonNull(theName, "Name cannot be null");
    if (Objects.requireNonNull(thePrice, "Price cannot be null").doubleValue() < 0) {
        throw new IllegalArgumentException("Price can't be less than 0");
    }
    myPrice = thePrice;

}


public Item(final String theName, final BigDecimal thePrice, final int theBulkQuantity,
            final BigDecimal theBulkPrice) {

    myName = Objects.requireNonNull(theName, "Name cannot be null");
    if (Objects.requireNonNull(thePrice, "Price cannot be null").doubleValue() < 0) {
        throw new IllegalArgumentException("Price can't be less than 0");
    }
    myPrice = thePrice;
    if (theBulkQuantity < 0) {
        throw new IllegalArgumentException("Bulk quantity cannot be less than 0");
    }
    myBulkQuantity = theBulkQuantity;
    if (Objects.requireNonNull(theBulkPrice, "Bulk price cannot be null").doubleValue() < 0) {
        throw new IllegalArgumentException("Bulk price cannot be less than 0");
    }
    myBulkPrice = theBulkPrice;

}

public boolean isBulk() {

    return false;
}

2 个答案:

答案 0 :(得分:3)

如果您将myBulkQuantity初始化为-1null并在isBulk()中检查其值,该怎么办?

答案 1 :(得分:1)

考虑使用Integer对象而不是int原语来表示批量数量的存在,其中null金额可能表示它不存在。如果域可以包括所有整数值,则这种区别尤其重要。此外,它可以防止选择&#34;魔术数字&#34;在你的代码中。

在Java 8中,您还可以通过更改getter签名来返回包含在Optional对象中的数据,从而指定您的getter来表示感兴趣的值可能是null,从而有效地减少了稍后您可能会在代码中引入NullPointerException

public class Item {
    private String name;
    private BigDecimal price;
    private Integer bulkQuantity;
    private BigDecimal bulkPrice;

    public Item(String name, BigDecimal price) {
        this.name = name;
        this.price = price;
    }

    public Item(String name, BigDecimal price, Integer bulkQuantity,
            BigDecimal bulkPrice) {
        this(name, price);
        this.bulkQuantity = bulkQuantity;
        this.bulkPrice = bulkPrice;
    }

    public Optional<Integer> getBulkQuantity() {
        return Optional.ofNullable(bulkQuantity);
    }

    public Optional<BigDecimal> getBulkPrice() {
        return Optional.ofNullable(bulkPrice);
    }

}