所以基本上我有一個例子,我創建了兩種方法,一種是從包含單位價格的類中返回全價,另一種是返回價格後貼現的方法。優化簡單的方法
public int getFullPrice(Product product){
int pricePerUnit = product.getPricePerUnit();
int fullPrice = this.quantity * pricePerUnit;
return fullPrice;
}
public int priceAfterDiscount(Product product){
int pricePerUnit = product.getPricePerUnit();
int fullPrice = this.quantity * pricePerUnit;
return fullPrice - this.discountRate;
}
我不知道這是否會是更好的做法是創建可以傳遞到第二個方法,或者這是否是不好的做法,因爲雖然我可重用代碼,如果第二種方法的第一種方法中的變量被執行了,它將不得不通過第一種方法之前?
public int getFullPrice(Product product){
int pricePerUnit = product.getPricePerUnit();
int fullPrice = this.quantity * pricePerUnit;
return fullPrice;
}
public int priceAfterDiscount(int fullPrice){
return fullPrice - this.discountRate;
}
我不是100%確定它是否從第一種方法中獲得fullPrice。或者我採取的方法是否不合理。我知道這樣做肯定會有一個更簡單的方式,而不需要重複代碼
這些方法不是產品類的一部分嗎?如果是這樣,那麼你不想給它一個Product參數,因爲它將使用當前實例的狀態'this'。 – 2015-03-13 18:16:08