官术网_书友最值得收藏!

Single responsibility principle

The single responsibility principle is an object-oriented design principle that states that a software module should have only one reason to change. In most cases, when writing Java code, we will apply this to classes.

The single responsibility principle can be regarded as a good practice for making encapsulation work at its best. A reason to change is something that triggers the need to change the code. If a class is subject to more than one reason to change, each of them might introduce changes that affect others. When those changes are managed separately but affect the same module, one set of changes might break the functionality related to the other reasons for change.

On the other hand, each responsibility/reason to change will add new dependencies, making the code less robust and harder to change.

In our example, we will use a database to persist the objects. Let's assume that, for the Car class, we will add methods to handle the database operations of create, read, update, and delete, as shown in the following diagram:

In this case, the Car will not only encapsulate the logic, but also the database operations (two responsibilities are two reasons to change). This will make our classes harder to maintain and test, as the code is tightly coupled. The Car class will depend on the database, so if in the future we want to change the database system, we have to change the Car code. This might generate errors in the Car logic.

Conversely, changing the Car logic might generate errors in the data persistence.

The solution would create two classes: one to encapsulate the Car logic and the other to be responsible for persistence:

主站蜘蛛池模板: 长葛市| 井研县| 原阳县| 吉水县| 永顺县| 余干县| 肥乡县| 南澳县| 铜山县| 宣武区| 曲麻莱县| 田东县| 侯马市| 平度市| 高雄市| 淄博市| 台南市| 双鸭山市| 黔南| 化德县| 广元市| 宜兰县| 义乌市| 彝良县| 长治县| 辽中县| 平南县| 财经| 呈贡县| 海原县| 永年县| 大港区| 吉安县| 信丰县| 双鸭山市| 滨海县| 蚌埠市| 太仆寺旗| 房产| 仁寿县| 宝丰县|