Re: inheritance is not for code-reuse (??)
On May 3, 8:52 am, Bart Simpson <123evergr...@terrace.com> wrote:
I remember reading on parashift recently, that "Composition is for code
reuse, inheritance is for flexibility" see
(http://www.parashift.com/c++-faq-lite/smalltalk.html#faq-30.4)
This confused me somewhat as I have always thought you get code reuse
"for free" with inheritance. Am I missing something?. Will someone care
to explain ??
"C++ Coding Standards" (Sutter and Alexandrescu) explains the
reasoning behind this advice, and cites as its basis, the "Liskov
Substitution Principle". Essentially, the LSP states that inheritiance
implies substitutability. So if A is a B, then A may inherit from B,
but if A just wants to re-use B's code, then A should make B a class
member.
I can also endorse this advice from my own experience. Having once
worked on a large software project that made heavy use of inheritance,
I can attest to the problems that can arise if perfect
substitutability is not required of a derived type. Without
substitutability, the small differences between base and derived
objects lead either to subtle bugs or otherwise require special
handling that violates encapsulation and that often requires a type-
specific implementation.
In fact, I would describe the problem like this: when inheriting from
a base class, the derived class effectively re-uses all of the base
class's implementation. But it is often the case that the programmer
really wants to re-use only a portion of the base's code - and not its
entire implementation. So what often happens in this situation is that
the programmer has to write code to prevent the derived class from re-
using code in the base class in ways that were neither anticipated nor
intended - so the programmer winds up writing more code - not less.
Greg