In objective C, I have a situation where I would like to have an abstract protocol (interface) with 5 methods and 4 properties, but at the same time, I’d like to have a common implementation of 3 of those 5 methods.
So my question is, is it ok to
1) have just an interface declaration with all the method and property declarations,
2) have a base class that adheres to that protocol (implements that interface) but also provides a common implementation of some of those classes, and only has empty stub method implementations for the rest of the methods, and then finally,
3) have a bunch of subclasses (from that base class), that will conform to that protocol – but – also inherit common method implementations -and – implement on their own those stub methods?
This is the pattern that is often used to address the lack of abstract classes in Objective C.
It is very common for the missing method stubs of the base implementation to raise an exception, to make sure that you catch incomplete implementations. See this answer on stack overflow for details of how it is commonly done.
is, is it ok to
1) have just an interface declaration with all the method and property
declarations,
Try it. You’ll find that without an @implementation section for any classes you use (even if you’re only subclassing them) you get an error. You need an @implementation for each class.
2) have a base class that adheres to that protocol (implements that
interface) but also provides a common implementation of some of those
classes, and only has empty stub method implementations for the rest
of the methods
Yes, you can certainly do that. Throw an exception in the stubs if you want to force subclasses to override them.
3) have a bunch of subclasses (from that base class), that will
conform to that protocol – but – also inherit common method
implementations -and – implement on their own those stub methods?
Sure, no problem there.
A protocol really is just a way to specify a set of methods. When you adopt a protocol in your class, you’re promising to provide those methods in your class, but you’re not promising anything about how those methods are implemented — the compiler won’t complain if they’re just empty methods that you override in subclasses.
Another possibility is to implement the common methods in your base class without adopting the protocol in question. Then adopt the protocol in each of your subclasses and implement any methods that you don’t inherit from the base class. That might not seem ideal, since each subclass has to adopt the protocol, but it may more accurately reflect the way the code works: the base class doesn’t adopt the protocol, only the subclasses do. If you happen to instantiate the base class and send it a -conformsToProtocol:
message, you’ll get NO
back.
2