Re: Maximum Accepted Layers/Levels of inheritance
Phlip <phlip2005@gmail.com> wrote:
Daniel T. wrote:
Make it as deep as you want.
You can't mean that. What's the deepest real-code example you have
available?
Note that our arch-enemy here is junior programmers writing
Hylidae --|> Anura --|> Amphibia --|> Chordata --|> Animalia
for no other reason than the target program contains taxa of tree-frogs. The
correct implementation would probably be the Composite Design Pattern,
which has 2 levels of inheritance.
However, I think that all base classes in
C++ should contain only pure-virtual functions and no data (i.e.,
interface classes.)
Isn't this putting the cart before the horse? What if, for some given
real-code situation, a few implementations should be in the base class.
Yes, that's just a convenience. Moving them down, at refactor time, should
be trivial. So just leave them there. The other arch-enemy here is junior
programmers behaving as if designs must never be changed...
To answer your questions, I've been known to write hierarchies 3-4
levels deep, and no I don't think it's putting the cart before the horse.
I have encountered no "real code situation" where "a few implementations
should be in the base class" in C++. Rather if several derived classes
all share common data and methods, I put them in a delegate class that
they all use. There is no "moving them down" because they were never in
the base class to begin with. (Note: my answer is different in a dynamic
typed language like Python.)
As for your tree-frog example. If I have a class that uses the Chordata
class and passes its Chordata objects to a class that uses the Amphibia
class and it passes objects to a class that uses the Anura class and it
passes them to a class that uses the Hylidae class, then I see nothing
wrong with the hierarchy as you have presented it. Such a situation is
obviously very rare. Maybe twice in the past 10 years.