Chapter 5. Class Design Guidelines
One of the primary goals of object-oriented (OO) programming is to model real-world systems in ways similar to the ways in which people actually think. Designing classes is the object-oriented way to create these models. Rather than using a structured, or
top-down
approach, where data and behavior are separate entities, the OO approach encapsulates the data and behavior into objects that interact with each other. Don't think of a problem as a sequence of events or routines operating on separate data files. Think of how your objects model real-world objects and how they interact with other real-world objects.
These interactions occur in a way similar to the interactions between real-world objects, such as people. Thus, when creating classes, you should design them in a way that represents the true behavior of the object. Let's use the
cabbie
example from previous chapters. The
Cab
class and the
Cabbie
class model a real-world entity. As
illustrated
in Figure 5.1, the
Cab
and the
Cabbie
objects encapsulate their data and behavior, and they interact through each other's public interfaces.
Figure 5.1. A cabbie and a cab are real-world objects.
When moving to OO programming for the first time, many people tend to still think in a structured way. One of the primary mistakes is to create a class that has behavior but no class data. In effect, they are creating a set of functions or subroutines in the structured model. This is not what you want to do, because it
violates
the concept of encapsulation.
As we have already discussed, OO programming supports the idea of making classes that are complete packages, encapsulating the data and behavior of a single entity. So, a class should represent a logical component, such as a taxicab.
This chapter
presents
several suggestions for designing solid classes. Obviously, no list such as this can be
considered
complete. You will undoubtedly add many guidelines to your personal list.
One of the better books pertaining to class design guidelines and suggestions is
Effective C: 50 Specific Ways to Improve Your Programs and Designs
by Scott Meyers. It offers important information about program design in a very
concise
manner.
|