Parallel Inheritance
There are two(+) associated classes A, B, and every sub type of A is associated with a (different?) sub type of B. e.g ProductEditor provides UI for a Product. Curtains and Books are different type of Products. CurtainEditor provides UI for Curtain. BookEditor provides UI for Book. And so on. Is this a CodeSmell?
If there is duplicate parallel relationship child classes, managing the duplicate relationship can be a problem.
class Product
{
}
class Book extends Product
{
}
class ProductEditor
{
private Product product;
public void setProduct(Product prd)
{
this.product = prd;
}
}
class BookEditor extends ProductEditor
{
// need to be careful?
private Book book;
public void setProduct(Book book)
{
this.product = prd; // need to call super also
}
}
BookEditor bookEditor = ...;
Product product = new Book(...);
bookEditor.setProduct(product); // calls base class method.
Book book = new Book(...);
bookEditor.setProduct(product); // calls chile class methods.
Adding duplicate relationship for convenience is bad. Apart for code duplication, if not done correctly, there could be dangling/spurious references.
How ever I don't think this is a code smell (due to its -ve meaning).In fact relation ships among parallel inheritance hiearchies is common in many frameworks (is a good smell?). Are not these relations cornerstone for template methods?When such relation ships exist,
- Document them and advise against duplicate relations.
- If needed provide a controlled relation ship managers for setting relations among the participant Objects (do we need a DIP for this?)