2015-03-13 100 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