2015-03-13 101 views
1

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

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。或者我采取的方法是否不合理。我知道这样做肯定会有一个更简单的方式,而不需要重复代码

+0

这些方法不是产品类的一部分吗?如果是这样,那么你不想给它一个Product参数,因为它将使用当前实例的状态'this'。 – 2015-03-13 18:16:08

回答

3

依赖副作用的代码行为,特别是以前执行的代码的副作用几乎总是一个坏主意。

如果在两个公共方法之间共享代码,更好的方法是将公共代码重构为私有或受保护的方法。

在这种情况下,折扣后的价格执行完全相同的全价计算计算,因此先调用它,然后发布流程以减少重复的代码。 (如果我明白了):

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

这帮助了大量,谢谢亚历克斯 – 2015-03-13 18:38:37

3

这个代替了吗?

public int getFullPrice(Product product){ 
    int pricePerUnit = product.getPricePerUnit(); 
    return this.quantity * pricePerUnit; 
} 

public int priceAfterDiscount(Product product){ 
    return getFullPrice(product) - this.discountRate; 
} 
+0

这似乎是合乎逻辑的,我只是不知道如何分辨什么是最有效的 – 2015-03-13 18:19:01

+2

@SmallLegend效率是你应该担心的最后一件事。考虑正确性,可读性和可维护性。在你上面的例子中,方法的调用者需要以正确的顺序调用2个方法来获得折扣价格。为什么要迫使他这样做,而不是提供一种方法为他做呢?如果有的话,你将不得不数百万次调用这些方法来开始看到差异。 – 2015-03-13 18:28:14

+0

好的欢呼的人 – 2015-03-13 18:38:13