Skip to Main Content
Prefactoring
book

Prefactoring

by Ken Pugh
September 2005
Intermediate to advanced content levelIntermediate to advanced
240 pages
6h 28m
English
O'Reilly Media, Inc.
Content preview from Prefactoring

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 ...

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Understanding Unittest.Mock

Understanding Unittest.Mock

Mario Corchero
Java™ Performance

Java™ Performance

Charlie Hunt, Binu John

Publisher Resources

ISBN: 0596008740Supplemental ContentCatalog PageErrata