所以基本上我有一个例子,我创建了两种方法,一种是从包含单位价格的类中返回全价,另一种是返回价格后贴现的方法。优化简单的方法
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