这是一个样例代码,它没有遵循单一职责原则。
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