Dao类的单一职责原则

3

这是一个样例代码,它没有遵循单一职责原则。

public class EmailSender
{
  public void SendEmail(string customerID, 
                       string emailNotificationType)
  {
    //STEP1: load customer details
    //STEP2: get email content
    //STEP3: send email (using SmtpClient class)
  }

  public string GetEmailContent(Customer customer, 
                 string emailNotificationType)
   {
    // Build the email notification content
   }
}

我同意,如果我需要执行以下操作,这将会带来问题:

-> Changes in the way, you are loading customer details.

-> Changes to the email content because of requirement enhancements / changes.

-> If there any change in the way you are sending the email instead of using SmtpClient class or something like that.

因此,我们需要应用单一职责原则来分离类。我完全同意这个原则。假设我需要创建三个类,如下:

EmailSender - 只关注发送电子邮件
CustomerRepository - 只关注获取客户数据
EmailContentBuilder - 解析电子邮件内容

但是,如果我有一个名为CustomerDao的Dao,目前我将与CustomerDao相关的所有CRUD操作都放在同一个类中,如下所示:

CustomerDao 类
- add()
- update()
- get()
- getAll()
- update()

我们需要在这里应用单一职责原则吗?如果是这样,如何应用于CustomerDao类?

谢谢,
Harry


我认为软件工程Stack Exchange可能更适合你的问题。 - Abra
@abra,我个人认为这也是一个编程问题,请告诉我您对CustomerDao的想法。 - Harry
请注意,将模式应用于正确的抽象级别非常重要。https://softwareengineering.stackexchange.com/questions/155627/something-confusing-about-single-responsibility-principle - arunvg
2
如果在单个类中使用,CRUD是很好的选择,而且你做得很好。除非你准备为小型操作维护那个代码库级别,否则不要将太多责任委托给其他类。而邮件发送器可以是静态的,并且可以用作工具类 :) - bananas
2个回答

0

你不想申请DAO,因为它只能做一件事。

良好的例子

来源

模式和原则是很好的东西,但如果使用不当,它们可能会让一个简单的问题变得像没有它们一样复杂。

SRP不应该被严格地理解。一个对象应该只有非常少的责任,而不是“一个”。 在这里 CustomerDao 只负责客户持久化,因此它只有一个职责。


0

尽管其名称为SRP,但其表达方式为“一个类应该只有一个变化的原因”。当在数据库表和业务对象之间进行映射更改时,DAO会发生变化,以避免违反SRP。

举个例子:如果业务逻辑发生变化,我们需要向对象添加更多数据:我们将字段添加到业务对象中,将列添加到数据库表中,当然还需要更改映射。然后我们很可能会更改单个DAO类的get/add/update方法。

为了清楚地理解这个原则,我建议阅读SOLID原则的原始来源:Robert Matin的书《敏捷软件开发:原则、模式和实践》。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接