Frage

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?

Link to the article: http://en.wikipedia.org/wiki/Call_super

War es hilfreich?

Lösung

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 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.

Andere Tipps

The gist of the problem is:

..However, the fact that the language itself may not be able to enforce all conditions prescribed on this call is what makes this an anti-pattern.

So the authors are anal about programmers having to do something that they believe the language should do for them.

The solution mentioned in the wikepedia article Call Super is:

A better approach to solve these issues is instead to use the template method pattern, where the superclass includes a purely abstract method that must be implemented by the subclasses and have the original method call that method

The problem is that Objective-c doesn't have virtual functions. It only has messages, so you can't implement what wikepedia suggests.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top