优化简单方法
Optimising simple methods
所以基本上我在这里有一个例子,我正在创建两种方法,一种是 returns 来自 class 的全价,其中包含单位价格,另一种方法是 returns价格post折扣
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。或者我采取的方法是否不合理。我知道肯定有一种更简单的方法可以做到这一点而无需重复代码
改成这个怎么样?
public int getFullPrice(Product product){
int pricePerUnit = product.getPricePerUnit();
return this.quantity * pricePerUnit;
}
public int priceAfterDiscount(Product product){
return getFullPrice(product) - this.discountRate;
}
依赖于副作用的代码行为,尤其是先前执行代码的副作用几乎总是一个坏主意。
如果两个 public 方法之间共享公共代码,更好的方法是将公共代码重构为私有或受保护的方法。
在这种情况下,您的折扣后价格执行的计算与全价计算完全相同,因此请先调用它,然后再调用 post 过程以减少重复代码。 (如果我理解的话):
public int getFullPrice(Product product){
int pricePerUnit = product.getPricePerUnit();
int fullPrice = this.quantity * pricePerUnit;
return fullPrice;
}
public int priceAfterDiscount(Product product){
return getFullPrice(product) - this.discountRate;
}
所以基本上我在这里有一个例子,我正在创建两种方法,一种是 returns 来自 class 的全价,其中包含单位价格,另一种方法是 returns价格post折扣
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。或者我采取的方法是否不合理。我知道肯定有一种更简单的方法可以做到这一点而无需重复代码
改成这个怎么样?
public int getFullPrice(Product product){
int pricePerUnit = product.getPricePerUnit();
return this.quantity * pricePerUnit;
}
public int priceAfterDiscount(Product product){
return getFullPrice(product) - this.discountRate;
}
依赖于副作用的代码行为,尤其是先前执行代码的副作用几乎总是一个坏主意。
如果两个 public 方法之间共享公共代码,更好的方法是将公共代码重构为私有或受保护的方法。
在这种情况下,您的折扣后价格执行的计算与全价计算完全相同,因此请先调用它,然后再调用 post 过程以减少重复代码。 (如果我理解的话):
public int getFullPrice(Product product){
int pricePerUnit = product.getPricePerUnit();
int fullPrice = this.quantity * pricePerUnit;
return fullPrice;
}
public int priceAfterDiscount(Product product){
return getFullPrice(product) - this.discountRate;
}