我在填充數據的位置有困難。何處填充數據?內部或外部方法?
以下2個樣的方法來計算報價的總價:
// example in javascript
function computePrice(quotation) {
var totalPrice = 0.00;
var items = quotation.getItems();
for (var i = 0; i < items.length; i++) {
totalPrice += items[i].getPrice();
}
return totalPrice;
}
QuotationDao.populateItems(quotation);
computePrice(quotation);
寫作的另一種方法是:
function computePrice(quotation) {
var totalPrice = 0.00;
// Populate items in the quotation from database
QuotationDao.populateItems(quotation);
var items = quotation.getItems();
for (var i = 0; i < items.length; i++) {
totalPrice += items[i].getPrice();
}
return totalPrice;
}
computePrice(quotation);
我問我的同事和接受不同的輸入。
方法#1是正確的,因爲代碼不應該檢索函數中的數據,除非該函數純粹是爲了檢索目的而創建的。
方法#1是正確的,因爲它允許單元測試。
方法#2是正確的,因爲在調用該方法之前不需要外部依賴項,該方法具有很高的內聚性。所有的方法都是不完整的,QuotationDao.populateItems(引用)應該像QuotationDao.getComputePriceData(引用)那樣在一個單獨的方法中,並將結果傳遞到computePrice(computePriceData)中;
您對我應該採取哪條路線有任何建議嗎?
謝謝你的魔杖。但呃..你會在哪裏填充報價單項目?裏面getTotalPrice或fetchQuotation或其他行之間,如: 報價q = DAO.fetchQutation(someCondition); DAO.populateQuotationItems(q); totalPrice = q.getTotalPrice(); – bryan
populateQuotation做什麼? –
嗯,1個報價通常有N個項目,如產品,數量,定價。 populateQuotationItems將填充特定報價的項目。只有在人口可以計算價格工作後。這是因爲沒有人口,報價將有0個項目,因爲他們還沒有從數據庫中檢索。 – bryan