'How to Solve Parallel Inheritance Hierarchies when we try to reuse code through inheritance
Recently in a job interview, they ask me "how to solve Parallel Inheritance Hierarchies when we try to reuse code through inheritance". I thought on Aggregation or Composition, but i was a little confused on making an example based on that.
So I decided to leave it pending to deepen concepts later, but after investigating it did not end up forming a precise answer to that question, could someone explain me a solution or an example to this?
Solution 1:[1]
The c2 wiki has a page on parallel inheritance hierarchies where ChaoKuoLin lists four possible solutions. I paraphrase them here, along with some context for each. See the original page for a full explanation including advantages, disadvantages, and examples.
- Keep the parallel hierarchies.
- When the hierarchies have separate responsibilities and each contains many methods.
- When maximum flexibility is required.
- Keep one of the hierarchies and collapse the other into a class.
- When one of the hierarchies can be reduced to a single class, for example by moving some methods to the other hierarchy.
- When one of the hierarchies contains few methods.
- Collapse the two hierarchies into one.
- When the hierarchies have similar responsibilities and each contains few methods.
- Keep a partial parallel hierarchy with the rest collapsed.
- When you want a middle ground among the previous solutions.
Another solution suggested in the wiki is Mix In and it is also suggested in How to solve parallel Inheritance in UI case?
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | jaco0646 |
