CS 535 Object-Oriented Programming & Design Fall Semester, 2000 Heuristics: Objects, Classes, Inheritance |
||
---|---|---|
© 2000, All Rights Reserved, SDSU & Roger Whitney San Diego State University -- This page last updated 29-Nov-00 |
Classes verses Objects
2.11 Be sure that the abstractions that you model are classes and not simply the roles that object play
5.15 Do not turn objects of a class into derived classes of the class. Be very suspicious of any derived class for which there is only one instance.
Is Mother a
3.9 Do not turn an operation into a class
public CurrencyAdd { int add( int a, int b ) { blah} } public CurrencyOperations { int add( int a, int b ) { blah} int subtract( int a, int b ) { blah} etc. }
Class name is a verb
3.2 Do not create god classes/objects in your systems
Inheritance
Terms
Derived class means child class or subclass
Base class means parent class or superclass
Some consider subclass & superclass ambiguous
A child class has can have more fields and methods
So:
5.2 Derived classes must have knowledge of their base classes by definition, but base classes should not know anything about their derived classes.
5.3 All data in a base class should be private; do not use protected data.
5.4 In theory, inheritance hierarchies should be deep – the deeper the better
Yo-yo Problem
|
Function |
|||
Class |
A
|
B
|
C
|
D
|
One |
Print
A, 1
B(); C(); |
|
Print
C, 1
|
|
Two |
|
Print
B, 2
D(); |
|
Print
D, 2
|
Three |
Print
A, 3
Two::A(); |
Print
B, 3
Two::B(); |
|
|
Four |
Print
A, 4
Three::A(); |
|
Print
C, 4
Three::C(); |
|
Five |
|
|
|
Print
D, 5
Four::D(); |
Yo-yo Problem
What is the result of the following program?
main() { Five yoyo; yoyo.A(); };Control Flow Trace for Function A in Class FiveOutput of Program
A,
4
A, 3 A, 1 B, 3 B, 2 |
D,
5
D, 2 C, 4 C, 1 |
5.6 All abstract classes must be base classes.
5.8 Factor the commonality of data, behavior, and/or interface as high as possible in the inheritance hierarchy.
5.9 If two or more classes share only common data (no common behavior), then that common data should be placed in a class that will be contained by each sharing class.
5.10 If two or more classes share common data and behavior, then those classes should inherit from a common base class that captures those data and methods.
5.11 If two or more classes share only a common interface (messages not methods), then they should inherit from a common base class only if they will be used polymorphically.
5.12 Explicit case analysis on the type of an object is usually an error. Polymorphism should be used in most of these cases.
In Java avoid
if x instanceof String blah else if x instanceof Vector more blah else if x instanceof StudentRecord even more blah
6.1 If you have an example of multiple inheritance in your design, assume you have made a mistake and prove otherwise