Composition vs Inheritance
In most object-oriented code inheritance is perhaps the most fundamental technique of object reuse, but it has several flaws. Object composition is much more robust, and often more appropriate but still hasn't become popular. I beleive that this can be attributed to the fact that object composition is more verbose than it needs be. I propose the introduction of a new feature to modern OOPLs to alleviate this: delegation of interface implementation.
A feature that I haven't really seen in many languages, and whose ommission has always struck me as odd, is the ability to delegate an interface implementation. In other words the ability to declare in a single line of code, the following pseudo-code:
implement IMyInterface through field fMyField
This feature would simply be syntactic sugar, but in many circumstances can save reams of code. It would also make object composition much more attractive to programmers as a method of reusing code.
Here are some of the more prominent problems with inheritance that motivate my desire to avoid it where possible:
- Inheritance in most OOPLs also implies subclassing/subtyping. Subtyping is not the same as inheritance (see: http://ctp.di.fct.unl.pt/mei/talmp/docs/InheritanceIsNotSubtyping.pdf ). Giving me subtyping when I want inheritance or code reuse is a bad thing. (especially in C++).
- Function overriding can break objects in very subtle ways. For example if the preconditions are tightened, or postconditions are loosened.
- Objects that depend on virtual function overriding to provide implementation strategies are very fragile and hard to test
- Multiple inheritance suffers from subtle problems (e.g. the diamond problem of repeated shared base classes).
- Forcing things into any given inheritance hierarchy is often an appropriate abstraction for one part of a system, but not for another.
Anyway, I still use inheritance because it is the best tool I've got, but I would really like delegation of interface implementation in my toolkit. Perhaps a prominent language designer on this site will consider the feature?
As a final thought, I am not much of a Ruby or Python programmer but I would be interested in learning how I could emulate this feature in Ruby and Python using their metaprogramming facilities.