07 July, 2009

When to use Class Inheritance in Programming

Last week I listened to a friend of mine complain about some straight-out-of-college programmers he had recently hired: "All of their code has 10 layers of inheritance. It's crazy trying to maintain their code!".

Unfortunately my friend is right: inheritance, although powerful - when used correctly, naturally tends to increase complexity.

Since your primary purpose as a programmer is to manage and reduce complexity, you should favors solutions that don't use inheritance.

At this point you're probably asking yourself: When am I supposed to use inheritance? How do I know if I'm using it correctly?Fortunately, the great Steve McConnel, has written 4 clear cut rules on when to use inheritance and when to use containment:
1. If multiple classes share common data but not behavior, create a common object that those classes contain.
2. If multiple classes share common behavior but not data, derive them from a common bases class that defines the common routines.
3. If multiple clses share commond data and behavior, inherit from a common base class that defines the common data and routines.
4. Inherit when you want the base class to control your itnerface; contain when you want to control the interface.

In summary, only inherit if the new class truly is-a more specialized version of the base class.

Oh, and one more piece of advice on inheritance: avoid multiple inheritance like the plague.

1 comments:

Unknown said...

Great points. This sounds really similar to what I was reading about at the end of last week. I ran into some Australian guy's blog that I really like following now.

He had a terrific post introducing the individual concepts that make up the SOLID acronym. The part that is most applicable to your discussion here is the Liskov Substitution Principle. It took me a little bit to get a decent understanding (and I had to read some about the preferred practice of composition), but I think it boils down to the same point you are making here.

Here is a link to the blog post I have been referring to: An introduction to the SOLID principles of OO design

Post a Comment