Object-Oriented Design
There are no absolute rules for developing object-oriented
software, but here are some guidelines.
Subclasses must pass the "is-a" test
- A subclass passes the "is-a" test when ALL
of the public methods of the base class hierarchy make sense for
the subclass. Ideally, a subclass wouldn't have any public
methods other than those inherited from the parent, some
possibly overridden. That way, the behavior of the subclass can
be invoked through a reference to the base class, thus achieving
true polymorphism.
- When only a subset of the base class' public methods make
sense for the subclass, then use delegation instead of
inheritance. If delegation is too tedious, then consider
extracting a new class from the methods that do make sense,
making both the former base class and the target class a
subclass of the new one.
Favor Composition Over Inheritance
- Inheritance is very powerful. Like Lord Acton said,
"Power corrupts, and absolute power corrupts absolutely."
- Use inheritance to achieve polymorphism. When you extend
one class from another, do so with the idea that you'll be
invoking the behavior of that class through a reference to the
base class.
- In general, try to use composition to extend behavior.
Composition amounts to creating classes with references to other
classes responsible for the specialized behavior. One class
delegates behavior to another.
- Strive to design each class so that it "does one thing and
one thing well." It should be readily apparent from the class'
source file what that one thing is. Ideally, it should be
readily apparent from the class' public interface. Even
ideally-er, it should be readily apparent from its name.
- Extending the behavior of a class can be accomplished in
two ways: inheritance and composition. Inheritance (used only
when all base class methods make sense for the subclass) locks
your behavior into a static structure. Sometimes this is
reasonable, but you should darn well know what the reason is
before you do it. In general, composition provides opportunites
for reuse that inheritance does not.
Jim Crossley
Last modified: Thu Dec 5 19:33:54 EST 2002