当前位置:网站首页>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 .
边栏推荐
- Summary of study notes for 2022 soft exam information security engineer preparation
- Junit单元测试
- C#版Selenium操作Chrome全屏模式显示(F11)
- Vscode matches and replaces the brackets
- The problem of "syntax error" when uipath executes insert statement is solved
- TCP connection is more than communicating with TCP protocol
- Kali2021 installation and basic configuration
- Flink analysis (II): analysis of backpressure mechanism
- Take you hand-in-hand to do intensive learning experiments -- knock the level in detail
- Flink analysis (I): basic concept analysis
猜你喜欢

C# NanoFramework 点灯和按键 之 ESP32

Jetpack compose 1.1 release, based on kotlin's Android UI Toolkit

Grafana 9 正式发布,更易用,更酷炫了!

Grafana 9 is officially released, which is easier to use and more cool!

Flink parsing (III): memory management

06个人研发的产品及推广-代码统计工具

C# WinForm中DataGridView单元格显示图片

连接局域网MySql

Wu Jun's trilogy insight (V) refusing fake workers

Pyspark operator processing spatial data full parsing (4): let's talk about spatial operations first
随机推荐
Shawshank's sense of redemption
轻量级计划服务工具研发与实践
Automatic operation and maintenance sharp weapon ansible Foundation
Essai de pénétration du Code à distance - essai du module b
连接局域网MySql
03 products and promotion developed by individuals - plan service configurator v3.0
PyTorch 提取中间层特征?
CTF逆向入门题——掷骰子
PySpark算子处理空间数据全解析(4): 先说说空间运算
05个人研发的产品及推广-数据同步工具
【逆向】脱壳后修复IAT并关闭ASLR
mysql高级(索引,视图,存储过程,函数,修改密码)
【MySQL入门】第四话 · 和kiko一起探索MySQL中的运算符
EasyRE WriteUp
Distributed (consistency protocol) leader election (dotnext.net.cluster implements raft election)
全网最全tcpdump和Wireshark抓包实践
03个人研发的产品及推广-计划服务配置器V3.0
自动答题 之 Selenium测试直接运行在浏览器中,就像真正的用户在操作一样。
Serial serialold parnew of JVM garbage collector
Jetpack compose 1.1 release, based on kotlin's Android UI Toolkit