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

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:

主站蜘蛛池模板: 商都县| 鹤庆县| 普安县| 扎赉特旗| 石嘴山市| 兴安县| 沁源县| 岚皋县| 韶关市| 南昌县| 珠海市| 新郑市| 泰和县| 平阴县| 桐柏县| 汨罗市| 怀仁县| 天门市| 漳州市| 鄂伦春自治旗| 连平县| 江都市| 嘉禾县| 湖南省| 阿拉善右旗| 杭州市| 页游| 黎川县| 永福县| 嘉鱼县| 大埔区| 云和县| 旬阳县| 垣曲县| 乌拉特前旗| 井研县| 富裕县| 综艺| 双江| 莱西市| 淮阳县|