5 ms·
It is likely I'm misunderstanding, but why would you use inheritance instead of composition in your example?
by 0x44 19y ago
It is likely I'm misunderstanding, but why would you use inheritance instead of composition in your example?
- ericwaller 19y agoThis is why prototype based languages allow software to model our experiences much more accurately. Inheritance seems to rely on a platonic ideal, i.e. there is some universal sense of chair (parent class) from which office chair, rocking chair inherit. In reality that's not how we think about chairs. We can imagine the first chair was a tree stump which was incrementally refined, eventually into office chair, rocking chair, etc. When we wish to add heated chairs to our application we can simply add a heating element to our chair prototype. We can even have heated office chairs, heated rocking chairs which use the same heating element prototype. Much more flexible.
- raganwald 19y agoThis approach fits the WAS-A relationship much better than the IS-A relationship. A heated chair WAS A chair, but we fitted it with a heater. It might still have enough in common with the original chair that you can use it without any change on your part, but you never know, there was that accident when we decided an EjectorSeat WAS A Chair last year...
- ambition 19y agoI bet the alternatives that were considered were: class Parent { void a() {...} void b() {...} void c() {...} void d() {...} ... void zzz() {...} } class B { Parent m_a; void a() {m_a.a()} void b() {m_a.b()} void c() {m_a.c()} void d() { specialized logic } ... void zzz() {m_a.zzz()} } vs. class B : Parent { void d() { specialized logic } }
- Retric 19y agoYour first example works fine until void a() Parent.a() calls Parent.d() and you need the code to call B.d(). An interface also works but you end up cutting and pasting a lot of the same code between the two classes.
- 0x44 19y agoI see. His example is meaningful only in a language that does not provide a convention for handling missing methods in the composed class. For instance, in ruby, I can distill your example to: class Parent def a; ... end def b; ... end def c; ... end ... def zzzz; ... end end class B def initialize @parent = Parent.new end def b; special logic end def method_missing(methodname) @parent.send(methodname) end end