the best class design

  • Thread starter Thread starter Mojtaba Faridzad
  • Start date Start date
M

Mojtaba Faridzad

Hi,

my question is about OO design. imagine we have 2 classes with some common
members and some different members. which one is better and why:

1) design class A completely and B as a drived from A with the different
members.

2) design a super class with common members then design class A and B drived
from this super class with their different members.
 
1) design class A completely and B as a drived from A with the different
members.

2) design a super class with common members then design class A and B drived
from this super class with their different members.

Inheritance should model 'isa' relationships. Is B a specialized type of
A? If not, then it should not inherit from it. It is ok for CDog and
CCat to both inherit from CAnimal, since both dogs and cats are kinds of
animals. But a dog is not a cat, so CDog should not inherit from CCat.

A common mistake is to use inheritance for the sake of code reuse. This
can lead to the wrong types of relationships in your class hierarchy.

H^2
 
Are the common members named the same but do they behave differently, or are
they the same? If A has members that aren't in B and B has members that
aren't in A, you can eliminate #1.

If they have members that are identical, I would derive them both from a
common parent class. So that all common code would exist in one place.

If you need to use polymorphism and the have members that behave
differently, I would derive them from an abstract superclass.

If you don't need polymorphism and their common members all behave
differently, I would just code them separately. Since there would be no
advantage to using inheritance.
 
Back
Top