Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 634
pencilCake Avatar asked Dec 07 '22 00:12

pencilCake


1 Answers

An object that can save itself to the database would violate SRP (Single responsibility principle).

Persistence is a responsibility all by itself and should be handled by dedicated classes.

This would be in addition to having LOW cohesion - the members that have to do with persistence have no relation to those that do not and would not be used in those methods of the class that do not deal with persistence.

like image 54
Oded Avatar answered Dec 12 '22 05:12

Oded