I’m not sure if I should create an abstract class and a series of descendants that inherit this abstract class, or define a protocol. What’s the best practice in Cocoa?
Share
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
It depends.
The abstract class + descendants pattern is known as a class cluster in Cocoa terminology. Well-known examples are
NSStringandNSArray. The main advantage of this approach is that you can implement methods on the base class that work in terms of a core set of methods and are inherited; for instance, a subclass ofNSStringonly needs to implement-lengthand-characterAtIndex:for all publicNSStringinstance methods to work (although it won’t be very efficient).The downside of this pattern is that implementations must inherit from the base class, which can be a severe restriction in a single-inheritance language.
A protocol, on the other hand, can be adopted by any class, but can’t provide a base implementation. It’s a lot like a statically-checked version of duck typing; by adopting a protocol you claim you can quack, and by requiring a protocol you can restrict a parameter to quack-capable classes without requiring a specific base class.
If you’re planning to provide a standard set of implementations for your abstraction, you probably want a class cluster. If you want to communicate with an open set of objects implementing your abstraction, you probably want a protocol.