Objective C 类别与开放/封闭原则

发布于 2024-11-03 00:59:49 字数 146 浏览 0 评论 0原文

根据开闭原则

。 。 。软件实体(类、模块、函数等)应该对扩展开放,但对修改关闭

那么我可以说类别严重违反了这一原则吗?

Accorinding to the Open/Closed principle

. . . software entities (classes, modules, functions, etc.) should be open for extension, but closed for modification

So can I say that the Category is a strong violation to this principle?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

半夏半凉 2024-11-10 00:59:49

我不明白怎么办。类别允许您添加依赖于现有界面的功能。它们不允许您对原始类进行任何真正的更改,它们只是提供一些语法糖,让您产生新方法已添加到类中的错觉。

换句话说,类别可以帮助您扩展类。他们不修改它。似乎它们强化了开放/封闭原则。

I don't see how. Categories allow you to add functionality which depends on the existing interface. They don't allow you to make any real changes to the original class, they just provide some syntactic sugar which gives you the illusion that new methods have been added to the class.

In other words, categories help you extend a class. They do not modify it. Seems like they reinforce the open/closed principle.

不念旧人 2024-11-10 00:59:49

我认为“关闭修改”的标准解释意味着“添加新功能不需要修改现有代码”。使用这种解释,类别不会违反开放/关闭原则,因为编写新的类别方法并不构成修改现有代码。

至于类别方法可以替换类中现有方法的特殊情况,它可能不会违反开放/关闭原则,但由于它是危险的而令人皱眉。这是该语言的“可以这样做,但不要这样做”的特性之一。

I think the standard interpretation of "closed for modification" means "adding new features doesn't require modifying existing code." Using that interpretation, categories don't violate the Open/Closed Principle because writing new category methods doesn't constitute modifying existing code.

As for the special case where category methods can replace existing methods on a class, it may not violate the Open/Closed Principle but it is frowned upon because it's dangerous. It's one of those "it's possible to do this, but don't" features of the language.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文