Pergunta

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?

Foi útil?

Solução

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?

Outras dicas

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.

In terms of Object Oriented Design only then no there is nothing wrong with the Save method being part of Product. It would actually be the preferred method within the Object Oriented Design world. And from a pure OO perspective you would not want it broken apart because that's more functional than object.

However, if you believe in the Dependency Inversion Principle which says high level modules should not depend upon low level modules; then a Save method would be appropriate but it should take an abstract Connection type as a parameter. This would give you an nice object model which includes a Save method but it would have no knowledge of the type of connection.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top