Member-only story
Prefer Composition Over Inheritance
Inheritance can get messy. Composition is flexible

Of the three OOP principles, inheritance was probably the second principle that you came to understand after encapsulation. It’s a pretty basic idea — you can augment an existing class while still using all the capabilities of the parent class. Easy as pie, right?
Interestingly, inheritance has somewhat fallen out of favor recently, giving way instead to the notion of composition. Inheritance is a powerful feature, but it can get out of control. Let’s look at an example to illustrate the point.
Out of Control Inheritance
Pretend you own a pizza shop. You want to write a system to manage all your pizzas. So, you start out with a base class:

Now, of course, that’s a nice abstract class, so we have to descend from it. We’ll assume that all self-respecting pizzas have tomato sauce, so we’ll create:

And of course, we’ll need cheese:

That’s great. But your customers will want more ingredients. Let’s start with pepperoni and mushrooms. We’ll end up with:

And, of course, some customers may want both, so you’ll need:

Now, let's add in sausages onions, anchovies, and black olives.
Hmm. This is going to get complicated really fast, isn’t it?