5.15 Mistaking Objects for Derived Classes

 <  Free Open Study  >  

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.

graphics/05fig32.gif

Heuristic 5.15

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.

graphics/05fig33.gif

 <  Free Open Study  >  


Object-Oriented Design Heuristics
Object-Oriented Design Heuristics (paperback)
ISBN: 0321774965
EAN: 2147483647
Year: 1996
Pages: 180

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net