您觉得《C# 敏捷原则、模式和实践》中的数据访问部分(使用 SQL Server)怎么样?
您如何看待这样的数据访问代码:
public void AddCusotmer(Cusotmer customer)
{
//save customer into database
...
// save payment type
SavePaymentType(customer);
//save other data
...
}
private void SavePaymentType(Customer customer)
{
if(customer.PaymentType is XXXPayment)
{
var payment = customer.PaymentType as XXXPayment;
//save payment to XXXPayments table in db
...
}
else if(customer.PaymentType is YYYPayment)
{
var payment = customer.PaymentType as XXXPayment;
//save payment to YYYPayments table in db
...
}
...
}
就我个人而言,我对这样的代码感觉不太好(使用“is”来检测类型来决定做什么),但是作者 Robert Martin 说没关系,因为它只是在 DAL 中,因此稍微违反 OCP 是可以接受的。
你觉得怎么样?
How do you think about data access code like this:
public void AddCusotmer(Cusotmer customer)
{
//save customer into database
...
// save payment type
SavePaymentType(customer);
//save other data
...
}
private void SavePaymentType(Customer customer)
{
if(customer.PaymentType is XXXPayment)
{
var payment = customer.PaymentType as XXXPayment;
//save payment to XXXPayments table in db
...
}
else if(customer.PaymentType is YYYPayment)
{
var payment = customer.PaymentType as XXXPayment;
//save payment to YYYPayments table in db
...
}
...
}
Personally, I'm not feeling very well with codes like this (using "is" to detect type to decide what to do), but Robert Martin the author says it's OK for it's only in DAL, so a little bit violation of OCP is acceptable.
How do you think?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这样的代码对我来说不太好。
您可能正在执行自己的 O/RM,因此不了解所有细节。
但使用接口可能会有所帮助(在这种情况下,付款实体将被 DAL 代码污染)......闻起来不太好。
因此,类的注册可能会完成这项工作:
在应用程序启动期间的某个地方,您可以注册 PaymentTypes:
因此,当您需要添加另一种付款类型时,您必须为其实现持久化程序并注册它。
对我来说,这看起来比原始代码好得多。
干杯。
The code like this doesn't smell good for me.
You are probably doing your own O/R-M so don't know all the details.
But using interfaces might help (in this case the Payment entity will be polutet with DAL code)... doesn't smell good eighter.
So probably registration of the classes would do the job:
And somewhere during app startup you could register the PaymentTypes:
So when you'll need to add another payment type you will have to implement persistor for it and register it.
This looks much better then the original code for me.
Cheers.