Single Responsibility Principle for Dao Classes

Viewed 525

This is a sample code which haven't followed the single responsibility principle,

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
   }
}

I agree, It will create the issue in case If I need to do following,

-> 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.

so we need to apply Single Responsibility Principle to separate the classes. I totally agree on this principle. Say I need to create three classes like

EmailSender - which only focus on sending email CustomerRepository - which only focus on fetching customer data EmailContentBuilder - which parse the email content

But say If I have a Dao like CustomerDao, As of now I have all the CRUD operations related to CustomerDao in the same class like below

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

Do we need to apply SingleResponsibilityPrinciple here? If so How to apply for CustomerDao class?

Thanks,
Harry

2 Answers

You do not want to apply to DAO because it only do one thing.

good example

sourse

Patterns and principles are great things, but used incorrectly they can make a simple problem just as complex as not having them.

SRP shouldn't be understood in a strict manner. One object should have very few responsibilities, not "one". Here CustomerDao is only responsible for Customer persistence, so it has only one responsibility.

Despite its name SRP is expressed as "A class should have only one reason to change". DAO is changed for the single reason: when mapping between database table and business object changes so DAO does not violate SRP.

Think of an example: business logic changes so that we need to add some more data to our object: we add fields to our business object, columns to database table and of course we need to change the mapping. We are likely to change get/add/update methods of our single DAO class then.

For clear understanding of the principle I would recommend reading the original source of SOLID principles: Robert Matin's book Agile Software Development, Principles, Patterns, and Practices.

Related