0
Completed

Explanation about why I should use „Composition over Inheritance“

Rebecca Werthine 4 years ago updated by Kent Hervey 3 years ago 4

I hear it everywhere and there are many explanation. But there are also many explanations which say that inheritance is also good. I would like to understand what is to use when and WHY. Your description on this site are soooo good. I wish me an explanation like this ;).


Thank you
many greetings

Quasselknopf ;) :)

+2

My answer: Flexibility.

Background

This is how I understand Inheritance and Composition:

  • Inheritance is an "is-a" relationship.
  • Composition is a "has-a" relationship.

Explain

It's easier to compose an object that does something ("has-a") than extends what it is ("is-a"). That is, inheritance strongly couples the child class with its parent class, and you always need to make sure the new code only extends the parent correctly. On contrast, composition allows you to move or add code more easily as you don't need to worry about failing to be a proper child class.

Usually, they both look good when you introduce some new classes; however, you will soon find out the composition code is much easier to modify when you make new changes.

It is possible to live without inheritance. The book "The Pragmatic Programmer" has a section about how to eliminate them entirely.

Reference

Here are some good references of this topic.

+1
Completed

Thanks, totally agree.

+1

Thank you very much!!!!! :) :)