oop – Can't understand the Single Responsibility Principle

Question:

In theory, everything is clear, but in practice there are always difficulties. They are connected with the fact that it is not clear on what scale this "One Duty" should be considered. Here I need to work with the database. If I create a DataBaseInteracting class can we assume that it has one responsibility? But then he writes data to the database and reads them from there and updates. Could it be better to create 3 classes: DataBaseWriter , DataBaseReader and DataBaseUpdater ?

Answer:

The Single Responsibility principle applies to almost any scale: method, class, module, subsystem, etc. When choosing a duty, as always, there must be some rationality. Moreover, one can sometimes deviate from all the principles. It will come with experience.

In your example, I would say that there is no need to split the DataBaseInteracting class according to actions. The duty to "ensure data storage" is quite atomic, in my opinion, and there is no need to divide it into read / write / update. However, it makes sense to divide in other planes. For example, if this class contains code for constructing SQL queries, then it should be placed in a separate class. Moreover, if you need support for several databases, then there should be several such classes.

That. if there is a need for some high-level change to "data storage", you will change the DataBaseInteracting class. If a bug with the construction of a suboptimal query is found, you will change the class that builds the queries and will not even touch DataBaseInteracting . If you need to maintain a new database, you just add a new class. Do you understand?

Moreover, all these classes must be in the DAL project. And this project should contain only that which relates to the logic of interaction with the storage (DB in your case). This will support SRP at the project level.

Scroll to Top