Why inheritance sucks

Software Design Add comments

I read the first part of a great article on why inheritance is not the best way to implement things. I like the Jedi references in the explaination. Everyone needs a DarkHippo!

The difference between is-a and has-a relationships is well known and a fundamental part of OOAD, but what is less well known is that almost every is-a relationship would be better off re-articulated as a has-a relationship.

Bad

// bad
class Jedi {
    function drawSabre():Sabre { … }
}
class DarkJedi extends Jedi {

    function crushTownspeople():void { … }
}
dj:DarkJedi = new DarkJedi();
dj.crushTownspeople();

Good

// good
class Jedi {
    function drawSabre():Sabre { ... }
}
class DarkPowers {
    function crushTownspeople():void { ... }
}
class DarkJedi extends Jedi {
    // DarkJedi has-a DarkPowers
    public var darkPowers:DarkPowers = new DarkPowers();
}
dj:DarkJedi = new DarkJedi();
dj.darkPowers.crushTownspeople();

Did You Enjoy This Post?

Be sure to grab my RSS feed so you don't miss out on more great articles.

This Post Was Brought To You By

How do I save time? I use FreshBooks for invoicing.

Get Information Technology magazine subscriptions and white papers for FREE!

Why inheritance sucks

Leave a Reply

WP Theme & Icons by N.Design Studio
Entries RSS Login