Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How many levels of inheritance [closed]

Are there any best practices regarding the maximum depth of the inheritance hierarchy for a framework and guidelines when to use multiple levels of inheritance or join them in a single class?

Some references to established practices/examples that worked well in the Java world would be nice in the answers as this is from the perspective of the community and frameworks surrounding Java.

like image 481
Cornelius Avatar asked Jan 19 '11 09:01

Cornelius


People also ask

How many levels of inheritance are there?

10.8 CLASSIFICATION OF INHERITANCE Hence, there would be two types: Single level inheritance: It will signify only two levels of classes. Base class and derived class. Multilevel inheritance: It will signify three or more levels of classes.

How many levels can you cast up or down your inheritance hierarchy?

From what I've seen (note: this isn't an official opinion, just my observations), 3-4 is a reasonable maximum.

How many levels of inheritance are allowed in Python?

Depending upon the number of child and parent classes involved, there are four types of inheritance in python.


2 Answers

You may be looking for a nice rule like "not more then 5 levels of inheritance" but I really doubt that there is such a rule. Objects usually model real world entities and the community of all those entities never agreed on a rule (as far as I know)...

One "best practice" is definitly: favor composition over inheritance. Following this guideline: define one interface and implementations with no further superclasses. All common fields and methods come with behaviour and strategies

On the other hand, we sometime model real world entities or structurs that already come with a deep hierarchy of entities. Classification of animals is one example or algebraic structures. A framework to model such existing structures would require a deep class hierarchy because it should follow the real world just to be understandable.

like image 147
Andreas Dolk Avatar answered Oct 05 '22 21:10

Andreas Dolk


From what I've seen (note: this isn't an official opinion, just my observations), 3-4 is a reasonable maximum.

Also, remember one important part from Effective Java:

Favor composition over inheritance

like image 44
darioo Avatar answered Oct 05 '22 20:10

darioo