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

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:

主站蜘蛛池模板: 临安市| 松潘县| 临泉县| 谢通门县| 循化| 普洱| 乐平市| 江孜县| 乐东| 闵行区| 杭州市| 尚义县| 济南市| 台湾省| 隆安县| 海林市| 嘉鱼县| 江安县| 思茅市| 巴塘县| 万源市| 揭东县| 湄潭县| 米林县| 贵州省| 香格里拉县| 克东县| 延寿县| 巨鹿县| 大化| 汶川县| 邳州市| 交城县| 屏山县| 福安市| 萍乡市| 积石山| 施甸县| 临沭县| 东台市| 泾阳县|