interfaces - Why should I prefer composition over inheritance? - Software Engineering Stack Exchange
- State “DONE” from “NEXT” [2017-03-28 Tue 09:56]
- Inheritance is just a way to easily implement Polymorphic behaviour
- Prefer a combination of composition and interface implementation
- Three kinds of polymorphism
- Hoc Polymorphism
-
Multiple procedures with the same name are defined in an ad hoc manner,
and where one is chosen by the language (perhaps the most specific).
- The least well behaved kind of polymorphism
- Parametric Polymorphism
-
The variation is defined by a parameter
- Composition is a kind of Parametric Polymorphism
- Subtype Polymorphism
-
A procedure defined on a given type, can also work on a whole family of
“subtypes” of that type.
- Inheritance is a kind of Subtype Polymorphism
- Should be governed by LSP
- The goal of polymorphism is generally code reuse but it is not the only way to achieve that goal.
- Good OOP applications can be written using only interface inheritance and
compositions
- Ban behaviour inheritance or design for it
- Prefer composition
- State “DONE” from “NEXT” [2017-07-24 Mon 12:23]
- What’s wrong with the inheritance?
- Multiple inheritance can lead to combinatorial explosion
- Mixins?
- The behaviour is not obvious
- Method name conflicts
- Mixins are good for defining meta behavior of a class
- Mixins are just a way to implicitly implement multiple inheritance
- Composition
- Nothing is Something
- Pros
- SRP
- high cohesion, low coupling
- Cons
- Verbose
- Need to use Factory or Builder to build objects
- It’s hard to chage to this mindset
- Go
- A programming language that doesn’t have inheritance by design but makes it possible
- Encourage composition
- Go
- Conclusion
- Inheritance is extremely overused
- Mixins can achieve implicit multi-inheritance, but it increases code complexity
- Composition is the most straightforward and clear approach to maintain dependencies between classes
You have to remember though that object-oriented programming is just a convention that some programmers came up with in order to help other programmers solve their problems. Don’t be a slave to these rules. Choose the solution that fits your situation best.