Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using the "Single Responsibility Principle" forces my containers to have public setters

I'm trying hard to design following the SOLID principles. What I've found is that when you use the "Single Responsibility Principle" (the S of SOLID) you usually have to split classes between the data containers and the data processors. For example If I have a class person with 5 properties that is read from DB instead of putting everything inside a class I create a Person class with the properties and another PersonReader class that reads that information from the database and creates the Person.

If I do that I have to open the Person properties so PersonReader could access them but then I have less encapsulation than putting everything inside a black box and making the properties only readable.

Am I missing something or is this a drawback of this principle?

Thanks in advance

EDIT: I've changed the person writer to a person reader because there was no need to make property setters public at the beginning.

like image 642
Ignacio Soler Garcia Avatar asked Dec 10 '10 18:12

Ignacio Soler Garcia


People also ask

What is the use of single responsibility principle?

As the name suggests, this principle states that each class should have one responsibility, one single purpose. This means that a class will do only one job, which leads us to conclude it should have only one reason to change.

What is true about single responsibility principle in agile design?

The Single Responsibility Principle (SRP) states that a class should have only one reason to change. It was first cited in this form by Robert C. Martin in an article that later formed a chapter in his Principles, Patterns, and Practices of Agile Software Development book.

Does single responsibility principle apply to methods?

The Single Responsibility Principle applies to the software that we develop on different levels: methods, classes, modules, and services (collectively, I'll call all these things components later in this article). So, the SRP states that each component should have a single responsibility.


1 Answers

Most data access strategies (ORM techniques) involve compromises of the kind you're describing. The least intrusive ones use reflection (or introspection, etc.) to populate your entities when they need to (when no public setters exist, for example).

Having said that, if your entities are only data containers (as in the anemic domain model), the single responsibility principle shouldn't really concern you much, since your objects don't have complex logic that would be spoiled by (or interfere with) data access code.

like image 69
Jeff Sternal Avatar answered Sep 21 '22 05:09

Jeff Sternal