开闭原则

Open closed principle

我理解这个原则指出一个模块对扩展开放但对修改关闭,当我们想要 upgrade/modify 某些 class 中的方法时,这一点很清楚 - 我们创建另一个 class 继承基础 class ,然后在此处重写基础方法以保持两种功能。

但是如果我们想向基础 class 添加另一个不同的方法呢?这是否被视为基础 class 的修改或扩展 - 可以将方法添加到基础 class 或者我们还应该创建继承基础 class 的新 class然后把新方法放在那里?

此外,关于向基础添加属性和字段的相同问题 class。

TL;DR
I think adding a new method inherently means that you cannot violate OCP; as OCP mainly focuses on the reckless overriding of existing methods.


Example:
Base class Calculator is inherited by MyCustomCalculator. The base class only has methods for adding, subtracting, multiplying and dividing two numbers.
Creating a new method in MyCustomCalculator, e.g. CalculateAverage(params int[]) does not violate OCP. It does not modify the logic behind any of the existing methods, it merely extends the methods that are provided by the calculator object.

新方法本质上不会改变旧方法。因此,他们不修改现有逻辑;然后简单地扩展可用的内容。

所以不,它没有(本质上)违反 OCP。

它几乎不可能违反 OCP,因为创建新事物(本质上)与修改现有事物完全不同。


虽然有些事情要注意:

  • 我能想到一个(有争议的)例外:重载。如果您创建一个重载现有方法的新方法,那么您有责任遵守重载规则。最值得注意的是,这意味着重载方法应该彼此执行完全相同的任务(重载方法只是基于不同的输入参数,但它们的处理和输出在功能上应该是等效的)。尽管我不能 100% 确定这是否违反了 OCP(因为它错误地扩展了一个基数 class),或者 SRP(因为它对processing/output 个重载方法)。好像两者兼而有之。
  • 即使您的新方法没有重载现有方法,同样的原则也适用。新方法是否与基地 class 的责任(intention/purpose)足够相关?因为如果差异很大,那么您可能会违反 SRP.

编辑

我漏掉了你的部分问题

is it ok to add the method to the base class or we should also create new class that inherits the base class and then put new method there?

这取决于上下文。对于我提供的 Calculator / MyCustomCalculator / CalculateAverage() 示例;我会本能地将它添加到基数 class,因为计算平均值是属于计算器职责的基本操作。

但是,如果我们正在讨论添加仅适用于复数 (MethodForComplexNumbers()) 的方法,那么我会提倡创建一个继承自 CalculatorComplexNumberCalculator 和实现 MethodForComplexNumbers().

不过,我认为这主要是由于SRP,而不是OCP