SOLID - SRP,一份工作或一个改变的原因

SOLID - SRP, One job or one reason for change

互联网上有很多关于 SRP 的混淆。

SRP 是否要求:

  1. classes/functions应该做一份工作?
  2. classes/functions 应该只有一个更改原因(而且我们不 不关心我们的 classes 正在执行多少工作,至少当我们 考虑 SRP)

例如

假设我们有一个 class 执行很多 work/jobs(我知道这很糟糕,我们不应该把所有东西都放在一个 class 中)

另外,我们假设这个 class 提供一个功能,并且这个功能只有一个更改原因,即更改原因只能来自一个参与者(例如我们的 CTO)

此代码是否仍适用于 SRP?

另外引用 Clean Architecture by Robert C. Martin

The SOLID principles, the Single Responsibility Principle (SRP) might be the least well understood. That’s likely because it has a particularly inappropriate name. It is too easy for programmers to hear the name and then assume that it means that every module should do just one thing.

Make no mistake, there is a principle like that. A function should do one, and onlyone, thing. We use that principle when we are refactoring large functions intosmaller functions; we use it at the lowest levels. But it is not one of the SOLID principles — it is not the SRP.

一如既往,这取决于。 "Single Responsibility"就是说,对一件事负责

"one thing" 可能是一个狭窄的领域,也可能是某种广泛的领域。一个简单的例子:

假设一个 class 计算字符串的加密签名,另一个 class 用于加密字符串。两个 classes 都尊重 SRP,因为他们每个人只做一件事。

如果您使用两种方法将它们绑定在一个 class 中,一种用于加密字符串,另一种用于计算签名,您显然违反了 SRP。因为加密和签名没有关系。

但现在想象一下,您有一个系统可以交换符合某些标准的签名和加密字符串。所以这两个函数当然是相关的,一个 class 必须处理这两个操作。

这个 class 的客户甚至对签名和加密之间的关系不感兴趣。客户端只需提供一个准备传输的字符串,然后 class 对字符串进行签名和加密。所以这个class当然尊重SRP,不管做两件事,签名和加密。

回到你的(坏)例子,class 执行了很多 work/jobs。当 class 执行的工作相关时,就有可能遵守 SRP。但是当工作不相关时,class 显然违反了 SRP。