Design Principle 3

#Object Oriented Programming design principle

“Favor composition over inheritance.”1

Common mistake in OOP is that its tempting to overuse class inheritance for everything. After all, OOP is all about inheritance and polymorphism for code reuse. However, most of the time programmers maintain or refactor code more than building the code base from scratch. You only build a program from square one once but you maintain indefinitely, and having a flexible system design is better than having a rigid class hierarchy that is difficult to maintain and improve.

Composition isolate parts of an entity without exposing the main class, allowing the isolated parts to be modified without affecting other parts that are fixed. In contrast, inheritance does not come very well with modification as the derived classes depend on the implementation of the parent class. It would be very time consuming to refactor codes that are tightly knitted, in that with one small change, can affect the entire class structure.

  1. Head First Design Pattern by Elisabeth Freeman and Kathy Sierra

    ↩︎