Search code examples
c#oopsingle-responsibility-principle

Is persistence responsibility in an object violating SRP?


I struggle with justifying whether this is violating SRP or not. The Employee class simply represents an employee in the system.

class Employee
{
  int id;
  string name;
  Date startDate;
  int departmentCode;


  void UpdateEmployeeInformation(some arguments) //updates the data in DB

  void DaysInTheCompany() //calculates now - startDate  difference

}

According to what I can read, it does violate SRP, but I am not sure why (I assume it is because the Update method is a different responsibility than just holding the data?


Solution

  • Yes. it is violating the SRP.

    The responsibility of Employee is to hold employee information, maybe some calculations, like DaysInTheCompany, but accessing a DB of File is not part of his responsibility.

    Your example is one of the easiest to identify.

    This post was useful to me. https://www.codeproject.com/Articles/587404/Understand-Single-Responsibility-and-Interface-Seg

    Your Employee class is just a container, You will populate this container in your business layer and pass it to the Data layer.

    I use a Service class, (EmployeeService), this class receives the Employee object and update the information in the database.

    In this link, you can see some ideas. https://softwareengineering.stackexchange.com/questions/156481/how-should-i-encapsulate-database-access