Class hierarchies should be deep and narrow

From CSSEMediaWiki
Jump to: navigation, search

A good class hierarchy design should be several layers deep. In a good design, a base class should not have a large number of direct children classes (eg a superclass having 28 subclasses). If a class hierarchy is not deep but is very wide, it is a sign that a change is needed.

A solution for solving this problem is to find some behaviour common to multiple child classes, and then extract these common behaviors into a parent class under the original base parent class. If the siblings provide different methods for the message, the methods should be broken into pieces and the common piece should be placed in the superclass while the rest should remain in the subclass.

An example related to this in Johnson and Foote 1988 is the View class in Smalltalk, which has 27 subclasses, some of which can contain subviews, but not all. The authors propose a concrete subclass of View called ViewWithSubviews which implements the subview functionality currently contained in View, and to make View an abstract superclass.

Riel's heuristic Favour deep hierarchies is derived from this idea.

See also

Personal tools