5.3. Appropriate Inheritance
When would we want to derive classes from CDRelease? When the classes behave differently. We want to deal with classes with a single interface (the base class), and not be concerned with the implementation in the derived classes.
A common indication that inheritance is desirable is the temptation to use switch statements in a class. For example, suppose Sam wanted to send an email to himself every time a CDRelease of type GoldieOldie or NewRelease was rented.
With only a single class, the code might employ a switch statement (or an equivalent set of if statements), as in the rental_notification( ) function shown in Example 5-6.
Example 5-6. Rental_notification method with switch
void rental_notification( )
{ switch(category_id)
{
case REGULAR_CD:
break;
case NEW_RELEASE_CD:
case GOLDIE_OLDIE_CD:
send_email( );
break;
default:
throw new ProgramException( );
}
|
With the array shown in Example 5-3, the creation of a new CDCategory involves just adding another entry to the array. With behavior dependent on the category such as in Example 5-6, each appearance of a switch statement needs to be changed. If we need one switch statement in the entire implementation of a class, we should consider inheritance. If the same switch occurs in multiple places, applying inheritance is in order. Suppose that Sam also wants an email when a GoldieOldie or NewRelease is returned. With different objects, the rental_return_notification( ) method would have a switch ...