Search code examples
c#.netoopservicecohesion

Does an object capapble to save itself into DataBase spoils the Cohesion of the class?


Speaking in terms of object oriented design, do you think to give a functionality of saving itself into Data-base to an object spoils the COHESION of the class?

Imagine:

Product p = new Product() 
          {
           Name = "Joy Rider", 
           Price = 100, 
           Currency = "USD"
          };

Do you think to save this product p onto DataBase is better to be done in this way:

 p.Save();

or in a way something like this:

 ProductServices.SaveProduct(p);

What do you think?


Solution

  • It does interfere with the single responsibility principle. The purpose of the Product class in your example is to represent a Product and the operations on that product. Interacting with the database is not a core part of the class' responsibility.

    Having the ProductServices class increases the maintainability of your code. Suppose the logic for saving objects in the database was to change (which it can) do you want to change every entity class in your system?