Object-oriented – Composition over inheritance but

compositioninheritanceinterfacesobject-orientedPHP

I'm trying to teach myself software engineering and coming up against some conflicting information which is confusing me.

I've been learning OOP and what abstract classes / Interfaces are and how to use them, but then I'm reading that one should 'favour composition over inheritance'. I understand composition is when one class composes / creates an object of another class to utilise / interact with that new object's functionality.

So my question is… Am I supposed to not use abstract classes and interfaces? To not create an abstract class and extend / inherit that abstract class's functionality in the concrete classes, and instead, just compose new objects to use the other class's functionality?

Or, am I supposed to use composition AND inherit from abstract classes; using them both in conjunction with each other? If so, could you provide some examples of how that would work and its benefits?

As I'm most comfortable with PHP, I'm using it to improve my OOP / SE skills before moving on to other languages and transferring my newly acquired SE skills, so examples using PHP would be most appreciated.

Best Answer

Composition over Inheritance means that when you want to re-use or extend functionality of an existing class, often it's more appropriate to create another class that will 'wrap' the existing class and use it's implementation internally. Decorator pattern is an example of this.

Inheritance isn't a good default way to deal with re-use scenarios because you often want to use just a part of a base class funtionality and the subclass can't support the whole contract of the base class in a way that satisfies Liskov substitution principle.

Template method is a good example of a case where inheritance is appropriate.

See this answer for guidelines on how to choose between composition and inheritance.

Related Topic