Is Inheritance Bad?
I hear many voices claiming that Inheritance is bad and recommending to use Composition instead. Their arguments have sense - I saw many examples on how to incorrectly use inheritance.
I would argue on one argument which implicates a tight coupling between a parent and extending class. Let's take classic Vehicle and Car extending Vehicle example. Can we say Car is close coupled with Vehicle? No, because Car is a Vehicle!
What do you think?
I would argue on one argument which implicates a tight coupling between a parent and extending class. Let's take classic Vehicle and Car extending Vehicle example. Can we say Car is close coupled with Vehicle? No, because Car is a Vehicle!
What do you think?
5 Comments:
My opinion is that inheritance is not bad if it is shallow. Once you start having 3 or more ancestors, the problem is better solved with composition. It allows more flexibility.
Thierry,
Thanks for your comment.
Take a classic example of object relation question. Should we have Employee inherited from Person, or should we use composition here? Is it a question of implementation, or a question of design?
For me, there is very little barrier between design phase and "implementation" phase. Actually both design and coding are implementation of our requirements. The difference we have is that we deal with higher-level decisions during design, and lower-level decisions during implementation. We meet with inheritance vs composition in both design (as in example earlier) and implementation.
How do you see the strong separation between implementation and "declaration" could be accomplished, and what it results to?
following dkrukovsky, Employee is just a 'facet' or 'aspect'a Person has, it's not a new kind of Person. Languages I know dont have clear semantics of expressing this nature, what can be done so far is having a Person Interfaces which both Employee and Person implement, and having a Employee composed by a Person.
The biggest issue I have with Inheritance is that it is overused.
if the relationship can accurately be described as a "is-a" relationship, then it's probably a good reason to use inheritance. But, many time developers use inheritance because 2 objects have 1 thing in common (and nothing else in common), and they don't have enough tools in their toolbox to solve the problem any other way (like delegates, interfaces, and patterns).
Roberto! Bill Venners described well-designed Person / Employee relations at
http://www.artima.com/designtechniques/compoinhP.html
Post a Comment
<< Home