Monday, August 10, 2009

a super solution

Like many developers, I favor Composition over Inheritance. Still, subclassing is a powerful tool, and I can't imagine abandoning it altogether. Knowing its pifalls, I try to make my intentions as clear as possible when I choose to use Inheritance.

When I read other-people's code, I tend to get confused by inherited variables. Say I'm skimming over a class with three members: width, height and color. I read method after method that mentions these members. Then all of the sudden, one lone method mentions position.

Huh? What's position? Why haven't I seen it before? I scroll around, looking for its definition, but I don't find it. Finally, I remember that I'm looking at a subclass. "Oh! Maybe position is defined in its parent class." I flip over to that class and, sure enough, there's position's declaration. (This must be a total nightmare in languages that support multiple inheritance.)

But I've now wasted brain cells on something other than the task at hand (whatever that was). I shouldn't have to go searching for vars.

To fix this in my own code, I'm going to start labeling inherited vars as with the prefix "super."

function foo() : void
var someValue : Number = width + super.position.x;

If I look at code like that, I know exactly where position comes from.

No comments:

Post a Comment