The Artima Developer Community
Sponsored Link

Designing with Interfaces
One Programmer's Struggle to Understand the Interface
by Bill Venners
First Published in JavaWorld, November 1998

<<  Page 5 of 6  >>

Advertisement

Choosing between composition and inheritance
As I described in last month's article, my basic approach to choosing between inheritance and composition is that I make sure inheritance models a permanent is-a relationship. The is-a relationship means that a subclass is a more specialized form of a superclass (that the superclass is a more general form of the subclass). For example, a SavingsAccount is-an Account. I believe that modeling all (and only) permanent is-a relationships with inheritance helps maximize the code flexibility, because doing so gives inheritance a clear meaning that can help other programmers understand your code.

My main design philosophy is that its primary goal should be to maximize code flexibility, defined as the ease with which code can be understood and changed. Although I state in last month's article that composition in general yields more flexible code than inheritance, I list reasons that show composition yielding code that's easier to change, but not necessarily easier to understand. Inheritance, if you use it just for is-a relationships, gives you the flexibility advantage that your code becomes easier to understand.

My feeling, therefore, is that the way to get maximum advantage of both inheritance and composition in your designs is to ask yourself if you have a permanent is-a relationship. If so, use inheritance. If not, use composition. For more details on this design guideline, read last month's article.

<<  Page 5 of 6  >>


Sponsored Links



Google
  Web Artima.com   
Copyright © 1996-2009 Artima, Inc. All Rights Reserved. - Privacy Policy - Terms of Use - Advertise with Us