Thomas Clayson
Thomas Clayson

Reputation: 29925

Subclassing private classes in a library

So we have a library with header files as below (for instance):

Public

Private

When this is imported into an app however it then complains that it can't find MyClass.h. This is fair enough. Its #imported into MyCustomClass.h and yet its hidden.

So I changed it to a forward class declaration @class MyClass. Now it complains that I can't use a forward declaration for a super class (also makes sense).

How can I get around this then? I need to subclass something, but I only want people using the library to have access to the child class, not the super class.

Upvotes: 1

Views: 540

Answers (1)

Mark Bernstein
Mark Bernstein

Reputation: 2080

You're writing a library, and you want clients to instantiate MyCustomClass which inherits from MyClass. But clients should not ever instantiate MyClass.

Approach 1: You don't actually need or want to hide MyClass. You just want to avoid instantiating instances of it.

  • a) Make its constructor private
  • b) Create a factory method that creates instances of MyCustomClass.

The factory might be part of MyClass, or it could be elsewhere.

@implemenation MyClass
+ (MyCustomClass*) createWith: (Param*) someData;

Approach 2: consider composition rather than inheritance. Let MyCustomClass own an object of type MyClass, and let it do all the work:

 @implementation MyCustomClass
 @property (nonatomic,strong) MyClass* myClassInstance;
 - (void) doSomething 
 {
      [self.myClassInstance doSomething];
 }

Since clients can't subclass MyClass anyway, the inheritance is an implementation detail. Don't inherit when you don't need to.

Approach 3: Are you sure you really want to expose MyCustomClass? Is it really an object, or is it a protocol? Perhaps your library should offer the interface publicly, and both MyClass and MyCustomClass are private implementations.

Upvotes: 1

Related Questions