- 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:

- Facebook Application Development with Graph API Cookbook
- Interactive Data Visualization with Python
- Spring Boot+Spring Cloud+Vue+Element項目實(shí)戰(zhàn):手把手教你開發(fā)權(quán)限管理系統(tǒng)
- 云原生Spring實(shí)戰(zhàn)
- 軟件工程
- Android底層接口與驅(qū)動開發(fā)技術(shù)詳解
- Julia 1.0 Programming Complete Reference Guide
- Python數(shù)據(jù)可視化之美:專業(yè)圖表繪制指南(全彩)
- AutoCAD基礎(chǔ)教程
- Python Social Media Analytics
- C Primer Plus(第6版)中文版【最新修訂版】
- Android初級應(yīng)用開發(fā)
- Learning Node.js for Mobile Application Development
- CISSP in 21 Days(Second Edition)
- MySQL 5.7從入門到精通(視頻教學(xué)版)(第2版)