我有存儲在一個文本文件,下面的模板:如何重構此代碼以使其更通用?
您好,感謝您購買的{一年} {使} {}模型。
year, make, and model
進來存儲在template configuration table
和實際值存儲在一個Car table
。
目前,我得到的是模板(year, make, and model)
使用,然後我從Car
表對他們的價值觀和我更換令牌({year}, {make}, {model})
與數據庫中的值的所有領域,所以它最終看起來像東西:
你好,感謝購買2013年本田思域。
這是所有罰款時,一切都從Car
表,因爲如果模板添加需要一個新的領域,像{color}
,我只是將它添加到template configuration table
和一切工作和template configuration table
是每個用戶,所以如果一個用戶不希望{color}
,這可以很容易地完成。我遇到的問題是當數據沒有從Car
來,但可能會從其他表來,例如:
您好,感謝您購買的{一年} {使} {}模型。
您的訂單號爲{} order_no,你可以聯繫{} customer_service_number
客戶服務,如果您有任何問題。
對於此示例的目的,讓我們假設{order_no}
來自一個orders
表和{customer_service_number}
來自一個CustomerService
表。
我想有這樣的方法:
var text = @"Hello, Thanks for Buying the {year} {make} {model}.
Your order number is {order_no} and you can contact customer service at {customer_service_number} if you have any problems.";
//This is for fields that are found directly on the Car object
foreach(var field in templateFields)
{
var val = car.GetType().GetProperty(field).GetValue(car,null);
text = text.Replace(field, val);
}
//Replace other fields
var order_no = order.GetOrderNo();
text = text.Replace("{order_no}",order_no);
var customer_service_number = customerService.GetCustomerServiceNumber();
text = text.Replace("{customer_service_number}",customer_service_number);
,如果每個人都希望看到的附加字段中的上述工作正常,但如果只有幾個用戶希望看到的order_no and/or the customer_service_number
一部分,然後調用一個或者兩者都沒有意義。
此外,如果客戶希望看到產生額外的信息,那我也有像另一個電話:
text = text.Replace("{number_of_oil_changes}",car.NumberOfOilChanges);
然後我結束了一堆根據不同的客戶有用的和/或無用的方法,那麼如何避免必須編寫所有這些額外的方法來獲取依賴於客戶的信息?
爲什麼客戶*不想*看到所有的信息? –
@DanTeesdale - 這是一個簡單的例子,但讓我們只是說,有些人不會爲額外的信息開車,有些人會這樣做。 – xaisoft
似乎更適合[codereview.se] – millimoose