DEV Community

Discussion on: Why composition is superior to inheritance as a way of sharing code

Collapse
 
ruidfigueiredo profile image
Rui Figueiredo

They might seem clearer but that's just if you think about inheritance as an IS-A relationship. For example it seems right to say "A Triangle is a Shape".

Even though it sounds right, you get very little from that if you look at inheritance in OOP for what it is. It's just "... declaration of
methods and variables in a subscope and it has nothing to do with ISA whatever, and the notion of ISA can be very confounding."

Not my words, they are Robert Martin's (known for the SOLID principles and the Agile methodology). He said them in this interview: hanselminutes.com/145/solid-princi...

Here's the transcript: s3.amazonaws.com/hanselminutes/han...

IS-A comes form AI's knowledge representation field, where there are algorithms that take advantage of that information to perform inferences (e.g. Semantic Nets).

In OOP there's no inference, so in the end a "Triangle" inheriting from a "Shape" class just means that the public and protected members of Shape are available in Triangle.

Inheritance is useful in some situations, but not when think about it using the "IS-A" perspective.

Collapse
 
lluismf profile image
Lluís Josep Martínez

The forget about the IS-A origin, in the real world a triangle is a kind of shape as well as a financial agent is a kind of person or a drug order is a kind of order. When defining entities belonging to a hierarchy I find it more natural to use inheritance instead of composition.