为什么“打电话给超级"?被维基百科认为是反模式吗? [英] Why is "call super" considered an anti-pattern according to Wikipedia?

查看:86
本文介绍了为什么“打电话给超级"?被维基百科认为是反模式吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

维基百科将超级呼叫"归类为反模式,我真的不明白为什么.该模式在objective-C/可可中经常使用;例如init/dealloc,drawrect,awakefromnib都要求您调用super.我在这里误解这个概念吗?

Wikipedia classifies "call super" as an anti-pattern, and I don't really understand why. The pattern is used pretty frequently in objective-C/cocoa; for example init/dealloc, drawrect, awakefromnib all require you to call super. Am I misunderstanding the concept here?

链接到文章: http://en.wikipedia.org/wiki/Call_super

推荐答案

该文章中所述,调用作为反模式的super方法是必要性,即父类期望"您重写该方法以使功能完整-但这样做并没有引起期望明确的.它还希望您调用超级实现.两者都是程序正常运行所必需的.

As it says in the article, it is the necessity to call the super method that is the antipattern, i.e. the super class "expects" you to override the method to make the functionality complete - but it does so without making this expectation explicit. And it also expects you to call the super implementation. Both are required for the program to work.

这是一种反模式,因为不能从代码中推断出程序员的意图.如果您的同事决定继续工作,他们将不知道您希望班级做什么,因此很可能会遇到问题和/或烦恼.

This is an antipattern, because the intent of the programmer cannot be deduced from the code. If your co-workers decided to work on it, they wouldn't know what you expected the class to do, and are therefore likely to encounter problems and/or irritations.

因此,如果您希望方法的某些部分被覆盖,但其他地方需要保留,则建议使用模板方法模式,其中将所有不能替换的内容保留在一个(私有)方法中,然后调用另一个方法-完全独立-为了使程序正常运行,必须实现 (在某些语言中,它甚至不会以其他方式编译).这样,您可以确保重要的事情仍然留在原处,并且扩展该类的任何人都将确切地知道要做什么,而对其他实现细节一无所知.

So if you expect some parts of a method to be overridden, but other things need to stay in place, it is recommended to use the template method pattern, where you keep all the things that must not be replaced in one (private) method, which then calls another one - completely separate -, which must be implemented in order for the program to work (in some languages, it won't even compile otherwise). That way, you make sure the important things remain where they have to be, and whoever extends the class will know exactly what to do, while remaining blissfully ignorant of the other implementation details.

Objective-C没有抽象或虚方法,但是如果调用super方法,则可以通过显式引发异常来达到相同的效果.这样,如果您的同事忘记重写该方法,该程序将崩溃-并崩溃,并显示他们将理解的错误消息,这将使他们比某些不稳定的问题更快,更轻松地理解和解决问题.由于功能不完整,行为没有解释.

Objective-C does not have abstract or virtual methods, but you can achieve the same effect by explicitly raising an exception if the super method is called. That way, if your co-workers forget to override the method, the program will crash - and it will crash with an error message that they will understand, and that will enable them to understand and fix the problem faster and more easily than some erratic behavior with no explanation, due to the functionality not being complete.

这篇关于为什么“打电话给超级"?被维基百科认为是反模式吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆