2015-10-14 31 views
0

我有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; 
} 
+0

我們不知道該方法做什麼。 –

+1

假設你不調用'myBulkPrice'或'myPrice',如果你調用** other **構造函數,你不能只檢查哪個值仍然是'null'嗎?話雖如此,你的'Item'類看起來好像試圖做不止一件事。你應該考慮把它抽象化,並創建自己的事情的「正常」和「批量」子類。 – azurefrog

回答

3

如果你初始化myBulkQuantity-1nullisBulk()檢查它的價值呢?

+1

而不是'0',因爲值可能爲0. – Mordechai

+0

完全正確@MouseEvent :) –

1

考慮使用Integer對象而不是int原語來表示大量數量的存在,其中null數量可能表示它不存在。如果域可能包含所有整數值,則此區別特別重要。此外,它可以防止在代碼中選擇「幻數」。

在Java 8中,您也可以指定你的getter表示通過改變吸氣簽名返回數據包在一個Optional對象,有效地減少了,你將會推出NullPointerException的機會,感興趣的值可能是null稍後在您的代碼:

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); 
    } 

}