我有2個構造函數,主要區別是存在BigDecimal bulkPrice
和int 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;
}
我們不知道該方法做什麼。 –
假設你不調用'myBulkPrice'或'myPrice',如果你調用** other **構造函數,你不能只檢查哪個值仍然是'null'嗎?話雖如此,你的'Item'類看起來好像試圖做不止一件事。你應該考慮把它抽象化,並創建自己的事情的「正常」和「批量」子類。 – azurefrog