【问题标题】:Single Responsibility Principle for Dao ClassesDao 类的单一职责原则
【发布时间】:2019-06-25 04:07:51
【问题描述】:

这是一个没有遵循单一职责原则的示例代码,

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 类
- 添加()
- 更新() - 获取()
- getAll()
- 更新()

我们需要在这里应用 SingleResponsibilityPrinciple 吗?如果是这样如何申请CustomerDao类?

谢谢,
哈利

【问题讨论】:

  • 我相信Software Engineering Stack Exchange 可能更适合您的问题。
  • @abra,恕我直言,我相信这也是一个程序性问题,请让我知道您对 CustomerDao 的看法
  • 检查这个,在正确的抽象级别应用模式很重要。 softwareengineering.stackexchange.com/questions/155627/…
  • CRUD 如果在单节课中使用很好,是的,你做得很好。除非您准备好为小型操作维护该级别的代码库,否则不要将太多责任委托给其他类。而mail Sender 可以是静态的,可以用作util类:)

标签: java design-patterns solid-principles single-responsibility-principle


【解决方案1】:

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

good example

sourse

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

不应以严格的方式理解 SRP。一个对象应该有很少的职责,而不是“一个”。 这里CustomerDao只负责客户持久化,所以它只有一个职责。

【讨论】:

    【解决方案2】:

    尽管它的名称 SRP 表示为“A class should have only one reason to change”。 DAO 更改的原因只有一个:当数据库表和业务对象之间的映射发生更改时,DAO 不会违反 SRP。

    考虑一个例子:业务逻辑发生变化,因此我们需要向对象添加更多数据:我们向业务对象添加字段,向数据库表添加列,当然我们需要更改映射。届时我们可能会更改单个 DAO 类的 get/add/update 方法。

    为了清楚地理解原理,我建议阅读 SOLID 原理的原始来源:Robert Matin 的书Agile Software Development, Principles, Patterns, and Practices

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-01-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多