Search code examples
objective-ccocoadesign-patternsanti-patterns

Why is "call super" considered an anti-pattern according to Wikipedia?


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


Solution

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