Avoid inheritance for optional containment

From CSSEMediaWiki
Jump to: navigation, search
Do not confuse optional containment with the need for inheritance. Modeling optional containment with inheritance will lead to a proliferation of classes. --Riel's Heuristic 5.18, Arthur Riel 1996

According to Riel, when it comes to optional components in objects, one should avoid using inheritance to create separate subclasses to model the base class with or without the optional component as this would lead to a proliferation of classes.

To illustrate, imagine a class called House that has optional components such as a heating system, a cooling system, an electrical system and a plumbing system. Modeling these optional components with inheritance will require one to create a subclass for each possible combination of a House that is using (or not using) a certain optional component. In the case of the imaginary house class, one would have to create 16 subclasses to account for all the possible configurations.

Instead of using inheritance, Riel suggests that the house class should contain references to objects that represent each optional component

See Also

Personal tools