5.1. Categories and Classes

Sam came by and said, "Oh, by the way, the rental period is different based on the category of a CDRelease."

"What is a category?" I asked.

"Oh," he said nonchalantly, "it could be a Golden Oldie, New Release, or Regular. Didn't I mention that before?"

"You must have—I just didn't remember it," I noted dryly.

You can approach this issue in a couple of ways—using different classes and using different objects. Using different classes is often the solution for when a programmer learns about inheritance. Once you have a shiny new hammer, every problem is a nail needing to be pounded. But not every problem is, or should be, solved with inheritance. Often an extra attribute in a class will do the trick.

5.1.1. Different Classes

We have three different categories: NewRelease, GoldenOldie, and Regular. Because there are three names, a designer might make these three separate classes. Since they are CDReleases, a natural thing to do is to form an inheritance hierarchy with a base class from which to derive each class. Figure 5-1 shows what an inheritance-oriented class hierarchy might look like.

Figure 5-1. A CDRelease inheritance hierarchy

The CDRelease abstract base class defines the base_rental_period( )abstract method. This method is implemented differently for each type of CD. The base class and the three derived classes would look like those shown ...

Get Prefactoring now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.