Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations biv343 on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

inheritance vs delegation 1

Status
Not open for further replies.

varocho

Programmer
Dec 4, 2000
238
US
What are the benefits and trade-offs of inheriting functionality from base classes vs. delegating this functionality to other classes?
 
OK, I'll start...

I think the two techniques are intended to address slightly different situations. Inheritance is used where there are one or (more typically) more objects that share a common set of functions (implemented in the base class) but also need to do some similar things differently (the bits that are added or overridden in the subclasses). But all the functions are directly associated with the type of object itself.

As for delegation, I tend to find this appearing when I find that a class is really implementing more than one discrete object. A new class can be extracted from the original one, which makes each one more cohesive, in that they more tightly implement the data and functions associated with one logically separate, er, thing.

I hope some of that makes sense! Was the question rhetorical or did you have a specific situation in mind?

Mike
 
Inheritance should be limited to those situations where you need objects to be of the same type. You shouldn't subclass JUST to reuse functionality.

As they say in the GoF book:
"Favor composition over inheritance"
 
There is also the is-a/has-a/contain-the-doubt analysis methodology. If it is-a thing, it is derrived from the thing. If it has-a thing, it contains the thing. When in doubt, contain the thing.

It's easy to remember, and works very well as a general rule of thumb.




Wil Mead
wmead@optonline.net

 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top