当前位置:网站首页>Single responsibility principle
Single responsibility principle
2022-07-06 17:39:00 【Wzzzzzzx】
paraphrase
At first glance, this principle , It is easy to misunderstand it as : Functions or classes should only maintain one capability . This is certainly an important design principle , But it's not Principle of single responsibility What you want to express . The initial description of this principle is : Any software module should have only one reason to be modified .
It may be a little difficult to understand , For software , Modification is endless . If only one reason can modify it , This reason should be avoided at the beginning of design , Be perfect . therefore , The reason here does not mean the intention of a change . But to , The objects served by this module , Is the reason for modifying the module . A further explanation is : Any software module should only be responsible for a certain kind of actors . This is also the meaning of responsibility in the name of the principle . there Actors It is the object served by this module , It can be a user or another module .
If a module or class needs to serve multiple actors , Then with the software iteration , Changes in actors' needs , The code of the module will expand infinitely , Code coupling will be greatly improved . In this regard, it is difficult for us to guarantee the modification of a certain actor , Can not affect the behavior of other actors . The end result is , Change a question , Leads to countless other questions , The project may lose maintenance .
The wrong case
The following is an example of non-compliance with the principle of single responsibility . This module is used to control a spacecraft .
class SpaceStation {
public:
// Constructors
SpaceStation();
void runSensor();
void useSupplies(string type, size_t quantity);
void reportSupplies();
void loadFuel(size_t quantity);
void reportFuel();
void activeThrusters();
};
When learning the database paradigm , You will encounter a picture that violates the paradigm Supertable . This kind of table puts all the fields together , Try to put all the data in one table , However, this will bring too much redundancy to the database , Insertion exception , Modify exceptions, etc . alike , This class is also a Super class , Designers try to use a class to solve problems about SpaceStation
All the needs of .
According to the principle of single responsibility , We can extract at least four actors from the current implementation of this class :sensors; supplies; fuel; thrusters
. Different actors will have different needs , Scientists will want to manage sensors
, The ground command center hopes to manage well supplies
, Engineers will want to manage fuel
, Astronauts hope to manage thrusters
.
From this, we can probably see the problem , Every actor wants to change SpaceStation
, If you don't stop it ,SpaceStation
It's going to get bigger and bigger , More and more complex , This is the modified “ reason ” That's too much , Consequences of violating the principle of single responsibility . indeed , In the initial stage , In this way, we can complete the task quickly , But subsequent maintenance will double the time saved at the beginning .
The solution is to separate the parts of the class responsible for different actors , Serve their respective actors , Only in this way can the problems mentioned above be avoided at the root .
Brief modification
class Sensor {
public:
void runSensor();
}
class Supplies {
public:
void useSupplies(string type, size_t quantity);
void reportSupplies();
}
class Fuel {
public:
void loadFuel(size_t quantity);
void reportFuel();
}
class Thrusters {
public:
void activeThrusters();
}
class SpaceStation {
public:
SpaceStation();
private:
Sensor sensor_control_;
Supplies supplies_control_;
Fuel fuel_control_;
Thrusters thruster_control_;
};
Now that four actors have been summarized , So the SpaceStation
Bring out the corresponding functions in , Put it where it should be , That is, the four classes shown in the code . This is not just a function encapsulation , More importantly, it maintains the single responsibility of the class , Each class has its own service object . The needs of service objects can be changed endlessly , But anyway , These changes will be controlled in one class , Will not have any impact on the outside . about SpaceStation
for , It doesn't need to care Sensor
or Fuel
How is it implemented internally , What it needs to focus on is the capabilities provided by these classes , Just ask for it on demand .
Of course , The only drawback may be that it looks a little complicated , It takes more management energy , But with the continuous development of the project , These drawbacks will be wiped out .
Such changes are not the final version , For example, we can abstract a Report
Interface ,Supplies
and Fuel
All inherit this interface to realize the corresponding reporting requirements . But for the explanation of the principle of completing single responsibility , The current revision is enough , We have successfully divided responsibilities , Drop it into the corresponding class .
summary
The principle of single responsibility is SOLID
The first major principle of the principle , Following this principle at all times can divide clear boundaries for each module , This can prevent the risk diffusion caused by modifying the code . And can realize information hiding , Hide unnecessary data inside , It is convenient for subsequent replacement and permission protection . what's more , A single responsibility can ensure that the module will not be destroyed by various modifications , Help maintain code maintainability .
边栏推荐
- Interpretation of Flink source code (II): Interpretation of jobgraph source code
- Display picture of DataGridView cell in C WinForm
- The NTFS format converter (convert.exe) is missing from the current system
- Akamai 反混淆篇
- Final review of information and network security (based on the key points given by the teacher)
- [elastic] elastic lacks xpack and cannot create template unknown setting index lifecycle. name index. lifecycle. rollover_ alias
- [VNCTF 2022]ezmath wp
- Essai de pénétration du Code à distance - essai du module b
- 分布式(一致性协议)之领导人选举( DotNext.Net.Cluster 实现Raft 选举 )
- [ASM] introduction and use of bytecode operation classwriter class
猜你喜欢
TCP connection is more than communicating with TCP protocol
【逆向初级】独树一帜
Distributed (consistency protocol) leader election (dotnext.net.cluster implements raft election)
Learn the wisdom of investment Masters
应用服务配置器(定时,数据库备份,文件备份,异地备份)
关于Selenium启动Chrome浏览器闪退问题
连接局域网MySql
JVM class loading subsystem
07个人研发的产品及推广-人力资源信息管理系统
List集合数据移除(List.subList.clear)
随机推荐
【MySQL入门】第一话 · 初入“数据库”大陆
全网最全tcpdump和Wireshark抓包实践
C# NanoFramework 点灯和按键 之 ESP32
Models used in data warehouse modeling and layered introduction
JVM garbage collector part 2
1. Introduction to JVM
05个人研发的产品及推广-数据同步工具
The most complete tcpdump and Wireshark packet capturing practice in the whole network
JUnit unit test
Akamai浅谈风控原理与解决方案
connection reset by peer
yarn : 无法加载文件 D:\ProgramFiles\nodejs\yarn.ps1,因为在此系统上禁止运行脚本
C# WinForm系列-Button简单使用
灵活报表v1.0(简单版)
[CISCN 2021 华南赛区]rsa Writeup
mysql高级(索引,视图,存储过程,函数,修改密码)
MySQL basic addition, deletion, modification and query of SQL statements
【ASM】字节码操作 ClassWriter 类介绍与使用
Example of batch update statement combining update and inner join in SQL Server
关于Selenium启动Chrome浏览器闪退问题