design - Where does idea that "inheritance is to be avoided" originate from? -
recently discussed defect mentioned here , 1 of parties said "yes, that's why books inheritance should avoided.
i've been using inheritance years , find useful , convenient in many design cases. i'm sure person arguing @ least misunderstood "books say".
is there idea inheritance kind of bad , should avoided? originate , can learn more?
i think might have meant inheritance can overused, in cases composition better solution. discussed in several books, e.g.
- effective java 2nd edition, item 16: favor composition on inheritance
inheritance powerful way achieve code reuse, not best tool job. used inappropriately, leads fragile software. safe use inheritance within package, subclass , superclass implementations under control of same programmers. safe use inheritance when extending classes designed , documented extension (item 17). inheriting ordinary concrete classes across package boundaries, however, dangerous. reminder, book uses word “inheritance” mean implementation inheritance (when 1 class extends another). problems discussed in item not apply interface inheritance (when class implements interface or 1 interface extends another).
unlike method invocation, inheritance violates encapsulation [snyder86]. in other words, subclass depends on implementation details of superclass proper function. superclass’s implementation may change release release, , if does, subclass may break, though code has not been touched. consequence, subclass must evolve in tandem superclass, unless superclass’s authors have designed , documented purpose of being extended.
- effective c++ 3rd edition has several items related this:
- item 32: make sure public inheritance models "is-a."
- item 34: differentiate between inheritance of interface , inheritance of implementation
- item 38: model "has-a" or "is-implemented-in-terms-of" through composition
Comments
Post a Comment