Why prefer composition over inheritance? What trade-offs are there for each approach? When should you choose inheritance over composition?
If you are looking for code reuse and the relationship between two classes is has-a then you should use composition rather than inheritance. Benefit of using composition in java is that we can control the visibility of other object to client classes and reuse only what we need.
[ Also on InfoWorld: Thread behavior in the JVM ] Because loosely coupled code offers more flexibility, many developers have learned that composition is a better technique than inheritance, but the truth is more complex.
The composition approach provides stronger encapsulation than inheritance, because a change to a back-end class does not necessarily break any code that relies on the front-end class. The main advantages of composition is, with carefully designed interfaces we can change references of back end classes at runtime.
The disadvantage of object composition is that the behavior of the system may be harder to understand just by looking at the source code. A system using object composition may be very dynamic in nature so it may require running the system to get a deeper understanding of how the different objects cooperate.
Prefer composition over inheritance as it is more malleable / easy to modify later, but do not use a compose-always approach. With composition, it's easy to change behavior on the fly with Dependency Injection / Setters. Inheritance is more rigid as most languages do not allow you to derive from more than one type. So the goose is more or less cooked once you derive from TypeA.
My acid test for the above is:
Does TypeB want to expose the complete interface (all public methods no less) of TypeA such that TypeB can be used where TypeA is expected? Indicates Inheritance.
Does TypeB want only some/part of the behavior exposed by TypeA? Indicates need for Composition.
Update: Just came back to my answer and it seems now that it is incomplete without a specific mention of Barbara Liskov's Liskov Substitution Principle as a test for 'Should I be inheriting from this type?'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With