THE PASZ.COM BLOG

Tuesday, August 23, 2005

The Perils of Inheritance


I've become wary about over-using inheritance. When I first learned OOP, I started to devise intricate inheritance relationships almost immediately. While they may have been very impressive in terms of complexity, they were also maintenance nightmares. As programmers, one of our primary goals is clarity in communication -- both for other programmers and also for ourselves 6 months down the road. Unfortunately, complicated inheritance chains can be anything but clear.

Let's use an example from a strategy/wargame (a la Command & Conquer).
Say I have a base class Unit that will describe every possible unit in the game (vehicles, soldiers, equipment, etc.) Now lets say I extend a Vehicle class from Unit, and then extend Tank from Vehicle.

Here's where the trouble starts. It can become difficult to figure out where methods are. If I need to fix a bug in the draw() method, how do I know where to look for it? I might look in the Tank class first and not find anything. Then I have to track back to Vehicle, which does have a draw() method. Unfortunately, the last line of Vehicle.draw() says super.draw(). Now I have to browse to my Unit base class and make some edits to the draw() method there.

First of all it's a waste of time to have to browse to 3 different files to track down a function. Morever, at this point we might have serious problems. I might have dozens of other Objects that were derived from Unit. Now that I've changed the fundamental drawing code for all of them, I will have to retest every one. So much for the benefits of modular OOP code. This sort of situation isn't any better than procedural programming. In fact, it might be worse!

If a feature is cool, there is a danger that you will overuse it. The best OOP libraries I've seen only have Inheritance hierarchies that are about 2 or 3 levels deep, max. The Java Class library comes to mind, as does AS2Lib. MFC, on the other hand, which uses inheritance like there's no tomorrow is generally considered bloated and confusing.

In a future blog entry, I will discuss Interfaces as an alternative to inheritance.

1 Comments:

Post a Comment

<< Home