Wednesday, September 30, 2009

Composition vs. Inheritance

Reusing existing code and avoiding code duplication lands itself to better, scalable and maintainable design and application architecture and is practiced by the Object-Oriented Programming (OOP) community. Inheritance is officially one of the three pillars of OOP, although composition isn't. The difference between the two is, inheritance depicts a "Is-A" relationship where composition is "Has-A" relationship.

As an example, let's take the object "book". I have a special type of book, called "technical book" which derives from the object "book". Certainly a technical book is a special type of book, but it is a book. Composition on the other hand is the having one object containing another object, hopefully related, but not necessarily. Check out the object of "Cover". The "book" has a "cover". Here is a C# code snippet.
   1:  public class TechnicalBook : Book
   2:  {
   3:    // every method & property of Book class (protected + public) 
   4:    // other methods and properties of TechnicalBook
   5:  }
   6:   
   7:  public class TechnicalBook
   8:  {
   9:     private technicalBookCover = new Cover();
  10:     
  11:     public string Title()
  12:     {
  13:        technicalBookCover.Title = "Design Patterns";
  14:        return technicalBookCover.Title;
  15:     } 
  16:  }
  17:   
  18:  public class Cover()
  19:  {
  20:     private string title;   
  21:   
  22:     public string Title { get return title; set title = value; }
  23:  }






Why is this important? Well, if we want to create applications which will be maintained over time and be used and extended in the future, I believe it is critical we make this distinction and model our applications accordingly.

My past experience had been more towards inheritance, but I resented the times that I have painted myself to a corner, since the dependencies created via inheritance becomes a burden to carry forward. Inheritance always exposes every public member in the base class while composition gives you an option to selectively choose, if any
By using Composition, the TechnicalBook class is insulated against changes of the inner class, Cover. With Inheritance any modifications to the base class Book, the TechnicalBook class is affected. If you want to bind the two classes, you can use an interface as a binding contract and let the two classes implement that interface.

In conclusion, Composition requires more work to expose the implementation of inner class objects, but the decoupling achieved by between the current type and the base type can quite valuable. Inheritance still holds true in cases where a clear "Is-A" relationship holds true, but in the long run things may need to be tweaked. And that's when you may want to favor Composition.

References: