- Design Patterns and Best Practices in Java
- Kamalmeet Singh Adrian Ianculescu LUCIAN PAUL TORJE
- 284字
- 2021-06-25 20:52:30
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:

- 深度實(shí)踐OpenStack:基于Python的OpenStack組件開發(fā)
- Python入門很簡單
- Learning Apache Mahout Classification
- Java EE 7 Performance Tuning and Optimization
- Linux:Embedded Development
- Android項(xiàng)目實(shí)戰(zhàn):手機(jī)安全衛(wèi)士開發(fā)案例解析
- Getting Started with Eclipse Juno
- Java高并發(fā)核心編程(卷1):NIO、Netty、Redis、ZooKeeper
- Android驅(qū)動(dòng)開發(fā)權(quán)威指南
- Processing創(chuàng)意編程指南
- 快速入門與進(jìn)階:Creo 4·0全實(shí)例精講
- UX Design for Mobile
- C語言程序設(shè)計(jì)
- Python編程入門(第3版)
- ASP.NET jQuery Cookbook(Second Edition)