Objective C 类别与开放/封闭原则
根据开闭原则
。 。 。软件实体(类、模块、函数等)应该对扩展开放,但对修改关闭
那么我可以说类别严重违反了这一原则吗?
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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我不明白怎么办。类别允许您添加依赖于现有界面的功能。它们不允许您对原始类进行任何真正的更改,它们只是提供一些语法糖,让您产生新方法已添加到类中的错觉。
换句话说,类别可以帮助您扩展类。他们不修改它。似乎它们强化了开放/封闭原则。
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.
我认为“关闭修改”的标准解释意味着“添加新功能不需要修改现有代码”。使用这种解释,类别不会违反开放/关闭原则,因为编写新的类别方法并不构成修改现有代码。
至于类别方法可以替换类中现有方法的特殊情况,它可能不会违反开放/关闭原则,但由于它是危险的而令人皱眉。这是该语言的“可以这样做,但不要这样做”的特性之一。
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.