当前位置:网站首页>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 .
边栏推荐
- Automatic operation and maintenance sharp weapon ansible Foundation
- Openharmony developer documentation open source project
- 【逆向】脱壳后修复IAT并关闭ASLR
- Flink analysis (II): analysis of backpressure mechanism
- Xin'an Second Edition: Chapter 23 cloud computing security requirements analysis and security protection engineering learning notes
- MySQL basic addition, deletion, modification and query of SQL statements
- JVM 垃圾回收器之Garbage First
- [rapid environment construction] openharmony 10 minute tutorial (cub pie)
- Essai de pénétration du Code à distance - essai du module b
- Akamai 反混淆篇
猜你喜欢
C version selenium operation chrome full screen mode display (F11)
How does wechat prevent withdrawal come true?
05个人研发的产品及推广-数据同步工具
Concept and basic knowledge of network layering
信息与网络安全期末复习(基于老师给的重点)
yarn : 无法加载文件 D:\ProgramFiles\nodejs\yarn.ps1,因为在此系统上禁止运行脚本
JVM garbage collector part 1
Start job: operation returned an invalid status code 'badrequst' or 'forbidden‘
【Elastic】Elastic缺少xpack无法创建模板 unknown setting index.lifecycle.name index.lifecycle.rollover_alias
C# WinForm系列-Button简单使用
随机推荐
BearPi-HM_ Nano development board "flower protector" case
CentOS7上Redis安装
Essai de pénétration du Code à distance - essai du module b
02个人研发的产品及推广-短信平台
07个人研发的产品及推广-人力资源信息管理系统
Total / statistics function of MySQL
Vscode replaces commas, or specific characters with newlines
[elastic] elastic lacks xpack and cannot create template unknown setting index lifecycle. name index. lifecycle. rollover_ alias
应用服务配置器(定时,数据库备份,文件备份,异地备份)
Kali2021 installation and basic configuration
Case: check the empty field [annotation + reflection + custom exception]
【MySQL入门】第三话 · MySQL中常见的数据类型
Brush questions during summer vacation, ouch ouch
微信防撤回是怎么实现的?
【ASM】字节码操作 ClassWriter 类介绍与使用
03 products and promotion developed by individuals - plan service configurator v3.0
Redis quick start
Selenium test of automatic answer runs directly in the browser, just like real users.
Display picture of DataGridView cell in C WinForm
自动化运维利器-Ansible-Playbook