Travis Swicegood

Why class inheritance sucks

Bernard Sumption has a post titled Inheritance is evil, and must be destroyed: part 1:

All of the pain caused by inheritance can be traced back to the fact that inheritance forces 'is-a' rather than 'has-a' relationships. If class R2Unit extends Droid, then a R2Unit is-a Droid. If class Jedi contains an instance variable of type Lightsabre, then a Jedi has-a Lightsabre.

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.

I couldn't have said it better myself. Remember that next time you type extends and re-think the implementation before taking the easy route. Unless, of course, you just want to be like Java ;-)

About

Travis Swicegood is a professional programmer and owner of Domain51, a web development company with a focus on non-profits, NGOs, and online activists. He doesn't change the world, he supports those who do.

He has personal a focus on web applications, performance, and stability; is author of Pragmatic Version Control using Git; and working on his second book. He has been using PHP; since '99 and still remembers how revolutionary PHP 4 was, but can't remember why. He's a TDD, open-source, and open government advocate—sometimes called a zealot—and lurker on many an open-source project mailing list when not learning other programming; languages; for fun, exploring his surroundings on bike, or tasting his latest kitchen and home-brew creations.

Contact
Around the Internet