OO Design: What should I choose - Composition vs Inheritance? and why?

ยท

1 min read

OO Design: What should I choose - Composition vs Inheritance? and why?

Inheritance (IS-A relationship)

  • Might violate encapsulation

  • Turns out bad when it comes to maintenance of code

  • Code duplication across subclasses

  • Changes in parent class affect the child classes

  • Less flexible

Composition (Has-A relationship)

  • Provides a lot of flexibility for changes in behavior

  • Encapsulate a family of algorithms into their own set of classes (sounds similar)

To summarize - referring to Strategy Design Pattern.

ย