From the course: Advanced Design Patterns: Design Principles

Unlock this course with a free trial

Join today to access over 22,400 courses taught by industry experts.

Favor composition over inheritance

Favor composition over inheritance

- [Instructor] Inheritance is main state of object orient design and programming. Within inheritance, we can avoid code duplication by inheriting behaviors. This a powerful technique. But it's a technique that can easily be overused. It's also a technique that can lead to designs that are far too rigged and not extensible. Our next design principle give us fore warning of this. Favor composition over inheritance. Or, as it's also known, HAS-A is better than IS-A. So remember, IS-A is an inheritance relationship. A dog is an animal. Or say, a taxi is an automobile. HAS-A is a relationship of composition. A dog has a owner. A taxi has a passenger. Composition can provide an alternative sub classing for extending behavior, and a powerful one. Let's look at an example. Consider a coffee shop that sells coffee. They have a simple class that represents their coffee. And they have a cost method and a prepare…

Contents