5.15 Mistaking Objects for Derived Classes
Consider the inheritance hierarchy shown in Figure 5.32. At first view the inheritance hierarchy looks correct. GeneralMotors, Ford, and Chrysler are all special types of car manufacturers. On second thought, is GeneralMotors really a special type of car manufacturer? Or is it an example of a car manufacturer? This is a classic error and it causes proliferation of classes. The designer of this hierarchy has accidentally turned what should have been objects of a class into derived classes of the class. If you have made this mistake, it will certainly manifest itself as a derived class for which there is only one instance in your system. How many GeneralMotors objects are there? Ford objects? Chrysler objects? The answer for all three classes is one. In this case they should have been objects. Keep in mind that not all derived classes that have only one instance in your system are manifestations of this error, but many will be.
Figure 5.32. Creating classes from objects.
Do not turn objects of a class into derived classes of the class. Be very suspicious of any derived class for which there is only one instance.
There is a temptation to state that in some domains the three objects of the class CarManufacturer should actually be derived classes due to some domain-specific reason. For example, perhaps GeneralMotors and Ford have very different accounting methods, and we feel this difference in behavior requires a polymorphic method (see Figure 5.33). Even in these cases, the three items in question are still objects. If the accounting methods are different, the developer is required to find some way of abstracting the differences into the data of the CarManufacturer class and to create a generic method that uses this data to manifest the appropriate behavior of each object. It makes no sense to create a derived class for which there can be only one object.
Figure 5.33. Using objects to generalize behavior.