1) Single Responsibility Principle (SRP, Single Responsibility Principle)

> There should never be more than one reason for a class to change.

You may have heard of a joke:

- Have you written code without bugs?

- Yes, I did it earlier: Hello World.

This paragraph tells us the truth: the simpler the code, the less likely it is to have a bug.

So how do we make code simple? By writing each line of code to do just one thing. In practice, we just let a class do just one thing. And if we can give this class a simple and intuitive name, the self-reporting of the code itself will be very good, I remember that Alibaba’s Java specification has requirements for naming, such as if a class uses a design pattern, It is required to embody the name of the design pattern in the name. At this time, the comments are redundant, and the code is easy for humans to read and to maintain.

Going back to the description of the single responsibility principle: Martin defines a responsibility as a reason to change, and concludes that a class or module should have one, and only one, reason to be changed (i.e. rewritten). As an example, consider a module that compiles and prints a report. Imagine such a module can be changed for two reasons. First, the content of the report could change. Second, the format of the report could change. These two things change for very different causes; one substantive, and one cosmetic. The single responsibility principle says that these two aspects of the problem are really two separate responsibilities, and should therefore be in separate classes or modules. It would be a bad design to couple two things that change for different reasons at different times.

The reason it is important to keep a class focused on a single concern is that it makes the class more robust. Continuing with the foregoing example, if there is a change to the report compilation process, there is greater danger that the printing code will break if it is part of the same class.

There is also a standard for judging whether a class conforms to the principle of single responsibility. It depends on the relevance of the elements in this class. You can’t have a writing function in a class that implements a repeater. Don’t think about it. He care the most will be checking the size of the clipboard. In other words, the clipboard itself should not be included in the class of repeaters, but exist as a service alone, and you can consider using the Repository mode.

High correlation means high cohesion and a smaller granularity in function.

The class mentioned here can refer to either an entity or a service. In the book of Domain-driven Design, Eric divides objects in the application into three types: values, entities, and services. An entity can be thought of as a combination of values, and a service is code that contains business logic.