1

正在阅读 SOLID 设计的 Open/Closed 原则,并对它的可维护性感到好奇。

假设我有从父类 A 继承的子类 B 和 C。B 具有 B 独有的方法,C 具有 C 独有的方法。父类 A 有两个子类使用的常用方法。

在未来的代码版本中,假设我们有一个新特性,它在 B 类和 C 类之间引入了一个公共方法。我们现在不能将该方法推到 A 类,因为它违反了原则的“关闭以供修改”部分。这似乎引入了代码冗余。不仅如此,从技术上讲,在B类和C类中增加这个新特性,是不是也违反了修改原则?

似乎使用 Open/Closed 方法,您最终会构建一个不必要的、级联的子类层次结构,仅仅是因为不允许对原始代码进行更改。这是一个正确的假设/理解吗?

4

2 回答 2

1

You don't have a crystal ball, you can't see the future and predict that a change request will happen.

However once a change request has been made, it is much more likely another change in that area will come later.

Lets take your cars example from the comment: The moment that the change request for all cars to now honk is received you should be considering if another such change will come in later. Assuming you decide it's a good chance that it will, there's only one thing for it, that's to refactor to make this whole situation Open for extension and Closed for modification. So that it's not only easy to add honking now, but you can add the next such feature with ease.

You are correct that to do apply this prematurely can bloat code and it will also receive plenty of YAGNI comments during code reviews.

于 2014-07-08T19:38:21.857 回答
0

似乎使用 Open/Closed 方法,您最终会构建一个不必要的、级联的子类层次结构,仅仅是因为不允许对原始代码进行更改。这是一个正确的假设/理解吗?

不,我不认为遵循开放/封闭原则会导致子类的级联层次结构。

首先,它只是一个原则或目标。有时,即使对于 SOLID 爱好者来说,向基类添加方法显然是“正确”的方法。

其次,基类中的许多方法(显然会导致更改)一开始就有点代码味道。您是否看过“偏好组合胜过继承”这句话?

于 2014-07-07T15:43:19.910 回答