是否有任何策略来划分应用 SRP 的责任?

Is there any strategy to partition the responsibilities to apply SRP?

是否有任何策略来划分 类 以应用单一职责原则?

在一个中等规模的团队中,我们正在开发一个可与不同类型的可穿戴设备连接的可穿戴设备管理器应用程序,比方说,Wearable1Wearable2(一次连接一个)。每个可穿戴设备都具有不同类型的数据交换功能。所以我决定根据可穿戴类型划分责任。即

interface Manager {
    // common functionalities
}

class Wearable1manager implements Manager {
    // Manages wearable1 specific functionalities
    // as well as wearable1 related capabilities
}

class Wearable2manager implements Manager {
    // Manages wearable2 specific functionalities
    // as well as wearable2 related capabilities
}

我的一位同事否认我的设计,说它违反了 Single Responsibility Principle (SRP),因为与能力相关的功能应该由单一能力经理处理。他的提议就像,

interface Manager {
    // common functionalities
}

class WearableManager implements Manager {
    // Manages wearable1 specific functionalities
    // as well as wearable2 specific functionalities
}

class CapabilityManager implements Manager {
    // Manages wearable1 related capabilities
    // as well as wearable2 related capabilities
}

基本上,我发现我们都强调应用单一职责原则,但我们分工职责的想法是基于不同方面的。当我需要根据我应该划分 类 的责任来决定时,我经常发现自己处于这种危急情况。所以我的问题是,

是否有任何特定的 OOP 设计指南可以帮助决定划分 类 以应用 SRP?还是这纯粹取决于经验?我希望应该有具体的步骤来分析和解决这种困惑。感谢有经验者的建议。

没有"responsibility"的定义。因此,没有这样的策略。但是,有:1) 勉强确定的常识,2) 对您所处环境的感觉。

根据我的个人经验,正确的问题是"why would I ever need to change this code?"。如果有不止一个(业务?)原因,那就会引发更多思考。

单一职责原则的定义:

The single responsibility principle is a computer programming principle that states that every module, class, or function[1] should have responsibility over a single part of the functionality provided by the software, and that responsibility should be entirely encapsulated by the class, module or function. All its services should be narrowly aligned with that responsibility. Robert C. Martin expresses the principle as, "A class should have only one reason to change,"[1] although, because of confusion around the word "reason" he more recently stated "This principle is about people.(Actor)"[2]

我们可以看到上面的定义中有responsibility的定义,我们把它表述成文字:

Responsibility equates to a logically bound part of the function provided by the software.

因此,如果您有与功能相关的功能,您应该在单个 class/module 中实现这些功能,因此您的同事是对的,您的初始代码将功能的实现分为两个不同的 Wearable Manager 类,这违反了原则,因为与能力相关的功能是一种责任。

不过,你说的也有道理,不同的可穿戴管理器有不同的能力。为了解决这个问题,您将需要可穿戴管理器实例的一个属性,该属性将标识它具有的功能。这可以是一个数组、一个字符串甚至是第三个管理器的实例,处理可穿戴设备的功能,因为您可以将功能和可穿戴设备之间的关系定义为一个单独的职责。

SRP 取决于您的职责。您需要定义您的案例中的责任。为此,您需要将您的功能划分为逻辑上绑定的分区(职责),然后一切都将适合到位。但是,如果你和你的同事做了不同的划分,那么你们两个心中的责任主体是不同的,讨论这个是一个明智的想法。

责任作为一个概念显然是可以定义的,但是,定义你的责任是你和你的同事的工作。对问题的经验和理解越多,分区就会越好。