Ansgar Esztermann
Ansgar Esztermann

Reputation: 251

Extending a class hierarchy

Recently, I've found a puzzling (to me) problem: Let's say I have a hierarchy of classes C1...C_n. Assume that at least some classes have more than one (direct) child class, but none have more than one parent (i.e. no multiple inheritance). I would like to change the hierarchy's behaviour. My first impulse would be to create subclasses D1...Dn and override methods as necessary, but there is one problem: when calling a newly overridden method, an actual Di may need to be passed as a formal D1 (or some level in between); this can be solved by subclassing C1 -> D1 -> D2 .... But when calling an unchanged method, any actual Di will need to be passed as a formal Ci, so we would have to derive each Di directly from Ci. Is there any elegant or generally accepted way to solve this riddle? If so, is there any way without resorting to multiple inheritance?

If there is no general way to achieve this, can the author of the original C hierarchy follow certain rules to provide this possibility?

For those who prefer a more practical approach, the original hierarchy implements SOAP in Ada. I am working on XML-RPC. From an abstract point of view, SOAP is a superset to XML-RPC, but the actual XML "on the wire" is quite different. In principle, one can perform most of the work by throwing away some of the data types (e.g. XML-RPC has one integer and one floating point type whereas SOAP has several of each), and replacing the routines that convert the remaining types to and from XML. However, due to the aforementioned inheritance problems, I ended up copying almost the entire SOAP hierarchy. The only code I've been able to re-use properly turned out to be the HTTP part (as it is not concerned only with text payloads, not with SOAP objects).

[Edit: Removed a simplifying assumption that would allow for a simple solution not applicable to the more general problem]

Upvotes: 0

Views: 97

Answers (1)

Marcin
Marcin

Reputation: 49846

The solution, because you assume single inheritance, and direct subclass relationships, is to just create D(1) as a subclass of C(n), in which case all Ds will also be in every C class.

In practice, the solution is not to create deep class hierarchies for no reason. If you're really into small classes, then use a system which accommodates multiple inheritance in some form.

Upvotes: 2

Related Questions