Inheritance is evil, and must be destroyed

When I built Animator.js, I got some flack for suggesting that inheritance is not a Good Thing. Keen to avoid a holy war I restated my position to ‘inheritance is often useful, but more often overused.’ Over the last few months I’ve been trying to figure out exactly when it should be used, and have concluded – at least for the kind of systems GUI developers build – never.

I’ve been working on a Flash port of Animator.js that’s been pumped up on performance enhancing drugs and given a flame thrower. It’s a fairly complex software component with around 30 classes, but it uses the Strategy Pattern instead of inheritance. I’ve grown fairly passionate about my anti-inheritance stand, and want to take some time to explain myself. In this article I rant for a few paragraphs in an attempt to persuade you not to use inheritance, and then show you how to use for Strategy Pattern for your own software.

The code samples for this article are in Actionscript but the concept applies just as much to JavaScript, or indeed any object oriented language.

Why inheritance sucks

Skip this and go straight to the code, if you like

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.

Eh?

Instead of extending a class and adding some functionality in the subclass, try putting the new functionality into its own class. Suppose you want to create a DarkJedi class; a dark Jedi is like a standard Jedi, but with dark powers too. The obvious way to do this is by extending the Jedi class and adding some appropriate methods:

// bad
class Jedi {
    function drawSabre():Sabre { ... }
}
class DarkJedi extends Jedi {
 
    function crushTownspeople():void { ... }
}
dj:DarkJedi = new DarkJedi();
dj.crushTownspeople();

This looks like the simplest approach, and it is at first. However, your dark powers are locked up inside the DarkJedi class. If you need to make a DarkDroid and a DarkSpaceship that can both also crush townspeople, you’re in trouble. These classes obviously can’t extend Jedi, so you have to duplicate townspeople crushing functionality across your whole DarkArmy or split it out into utility functions that you call from every crushTownspeople method. Either way, it gets complicated.

Now suppose you had done it like this:

// 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();

Everything that was possible in the first version is still possible in the second, but because DarkPowers is a separate class, there’s no limit on what kind of object can be evil:

class DarkHippo {
    public var darkPowers:DarkPowers = new DarkPowers();
    public function capsizeCanoe(canoe:Canoe):void {}
}

Yeah, but I don’t make Jedis. Or hippos.

Good point, but the problem above happens everywhere that inheritance does. I’ll give an example from the Flash player API because I consider Actionscript 3.0 is one of the most beautiful works of software engineering I have used in recent years, and if the team that made it can’t get inheritance to behave properly, how can the rest of us be expected to?

Here are 2 examples of use of inheritance, one appropriate and one not, and by ‘appropriate’ I mean that the problems that inheritance inevitably ends up causing are probably outweighed by the lower complexity.

Good inheritance: DisplayObjects

In Flash the DisplayObject hierarchy is a set of classes that represent the different kinds of on-screen object:

The DisplayObject hierarchy is a good use of inheritance. MovieClip extends Sprite and adds a timeline. A MovieClip is-a Sprite through and through: the fundamental defining purpose of a MovieClip is to be ‘a new kind of Sprite’. A MovieClip can always be used in place of a Sprite, it has the same methods and the same capabilities as a sprite, it is drawn on-screen like a Sprite; it just adds some extra timeline functionality on top.

More importantly, you generally don’t need to use the timeline features in the MovieClip class independently of the on-screen drawing features of the Sprite class.

It’s not all perfect. Last week I wanted to add some common functionality to both MovieClips and Sprites, but I couldn’t because it’s not possible to modify the DisplayObjectContainer base class that both these classes extend (and I refuse to monkey patch). In the end I had to use MovieClips where Sprites would do, which is inefficient.

It would be possible to re-articulate this relationship as has-a: the functionality in the MovieClip class would be split into a Timeline class, and MovieClip would extend Sprite with a public ‘timeline’ property.

// old style:
mc.goToAndPlay("shizzle");
// would become:
mc.timeline.goToAndPlay("shizzle");

But the existing version works well enough, and I think that the Flash API architect(s) made the right decision.

Bad inheritance: EventDispatcher

In flash, code to dispatch DOM events is contained in the EventDispatcher class.

EventDispatcher is a bad use of inheritance because in order to dispatch events, classes extend EventDispatcher. This is an incorrect analysis: just because a class can dispatch events, it does mean that fundamental defining purpose of the class is to be ‘a new kind of EventDispatcher’. Chances are that the class has a different fundamental purpose and the ability to dispatch events is secondary to the main purpose of the object.

This is fine for DisplayObjects, because all DisplayObjects dispatch events, and DisplayObject extends EventDispatcher, but what do you do if you want to dispatch events from an object that cannot extend EventDispatcher because it is already extending something else, perhaps Array for example? In this case, you must jump through hoops with the IEventDispatcher interface and a lot of extra boilerplate code.

This problem would not occur if instead of extending EventDispatcher in order to dispatch events, a class had a public property ‘events’ that contained an EventDispatcher. Instead of calling foo.addEventListener(), you would call foo.events.addListener(). This could either be a convention, or could be enforced with an interface. Now any class can participate in the event system just by adding a public property, because the relationship has been re-articulated from ‘x is an EventDispatcher’ to ‘x has an event dispatcher’.

(In all fairness to the Flash player API team, they made this decision because they were following the DOM Events specification, which requires that methods like addEventListener exist on the DOM nodes themselves, not as a separate events object)

Enough already, show me the code!

An example

Suppose you have a Ball class that implements a red Ball. You extend this class to make a BouncingBall class that, well, bounces. You again extend Ball to make a FadingBall class that fades in and out. Don’t ask me why, let’s just assume your client is strange. It might look something like this (the ball, not the client):

class Ball extends MovieClip {    
    function Ball() {
        graphics.beginFill(0xAA0000);
        graphics.drawCircle(0, 0, 20);
        graphics.endFill();
    }
}
class BouncingBall extends Ball {
    private var frame:int = 0;
    function BouncingBall() {
        addEventListener(Event.ENTER_FRAME, setPosition);
    }
    private function setPosition(e:Event):void {
        frame++;
        this.y = 280 - Math.abs(Math.cos(frame / 15) * 200);
    }
}
class FadingBall extends Ball {
    private var frame:int = 0;
    function FadingBall() {
        addEventListener(Event.ENTER_FRAME, setAlpha);
    }
    private function setAlpha(e:Event):void {
        frame++;
        this.alpha = Math.abs(Math.cos(frame / 15));
    }
}

Now suppose you want to make a ball that bounces and fades. Feck. Your problem here is that bouncing and fading balls aren’t really new kinds of ball, they’re new ways that the same ball behaves. The ball has-a bouncing behavior. Using inheritance, the code that handles bouncing and fading is locked up in the BouncingBall and FadingBall classes and can’t be used elsewhere.

If you’re paying any attention you know the solution by now:

// To create a bouncing and fading ball:
// var d = new StrategyBall();
// d.yMotionStrategy = new AbsSineStrategy(80, 200);
// d.alphaStrategy = new AbsSineStrategy(0, 1);
class StrategyBall extends MovieClip {
 
    public var yMotionStrategy:NumberSequenceStrategy;
    public var alphaStrategy:NumberSequenceStrategy;
 
    function StrategyBall() {
        graphics.beginFill(0xAA0000);
        graphics.drawCircle(0, 0, 20);
        graphics.endFill();
        addEventListener(Event.ENTER_FRAME, handleEnterFrame);
    }
 
    private function handleEnterFrame(e:Event):void {
        if (yMotionStrategy != null) {
            y = yMotionStrategy.nextValue();
        }
        if (alphaStrategy != null) {
            alpha = alphaStrategy.nextValue();
        }
    }
}
interface NumberSequenceStrategy {
    function nextValue():Number;
}
// Note how one class is used for both the fading and bouncing behavior - componentisation allows
// for greater code reuse
class AbsSineStrategy implements NumberSequenceStrategy {
 
    private var frame:int = 0;
    private var from:Number;
    private var to:Number;
 
    public function AbsSineStrategy(from:Number, to:Number) {
        this.from = from;
        this.to = to;
    }
 
    public function nextValue():Number {
        frame++;
        return to + Math.abs(Math.sin(frame / 15)) * (from - to);
    }
}

Apart from being able to make a bouncing, fading ball, there are 2 huge benefits of this solution:

  1. You can change the behaviour of each ball at runtime: a bouncing ball can become a fading ball at any time.
  2. You can reuse number generation algorithms between properties – note how there is only one number generation algorithm – AbsSineStrategy – is parametrised with the too and from values so that it can be use to control alpha or height.

How we got here

Why do people use inheritance?

JavaScript makes inheritance a pain in the ass to implement, so why is it so popular among frameworks? Part of the problem is that JavaScript has always looked like a flimsy lightweight scripting language next to Java and its strongly typed kin; keen to prove that they are using a real language for big people, JavaScript developers have rushed to adopt an OO feature that was never very good in the first place. Strongly typed languages don’t use inheritance because it’s a good idea, they use it for 3 bad reasons:

1. Because they have to. Java is littered with situations where, for example, a method requires a source of input so takes an InputStream parameter. InputStream should be an interface, but it’s not, it’s a class. Therefore if you want to pass your own input into such a method you have to create a new subclass of InputStream, or the program won’t compile.

2. Some of the few places where inheritance is appropriate are found in designing large frameworks like the HTML DOM and Flash’s DisplayObject hierarchy: the kind of systems new web developers are exposed to. People see these when they are learning to program and assume that that’s how it should be done (I know I did)

3. Sheer force of habit: some <http://en.wikipedia.org/wiki/Simula> people<http://en.wikipedia.org/wiki/Smalltalk> in the 60’s decided it was a good idea, and it’s too much effort to stop.

That’s enough theory – in my next Article I’ll actually do something useful with all this stuff!

Download the code for this article

Recommended article

A fascinating and detailed account of the move from concrete inheritance to composition in game programming.

101 thoughts on “Inheritance is evil, and must be destroyed”

  1. I read the article. Some programming languages support multiple inheritance — a new class can inherit from both bouncing ball and fading ball, for example. Granted this is sort of theoretical, since JS does not support multiple inheritance, but if you were programming in a language that did, would that change your view of inheritance?

  2. Actually JS can support a simple kind of multiple inheritance, since methods can be dynamically copied from one class to another. It’s far from ideal though.

    To answer your question, I think that while multiple inheritance eases the pain of inheritance a bit, it still encourages a “one object does everything” style of development.

    Conversely, using the Strategy Pattern encourages splitting up the problem into simple well encapsulated components, and is in my opinion a superior solution in every respect except performance.

    Take the example in the article: multiple inheritance would have let you create a bouncing fading ball, but it wouldn’t have helped you in splitting the number generation strategy out into a separate class (AbsSineStrategy) behind an interface (NumberSequenceStrategy) that lets you start building up a library of motion strategies that can work for fading, bouncing or anything else that requires a sequence of numbers.

  3. This article reminded me about Ruby way of doing things. And if your point is he ultimate truth — then it seems that Ruby the language shares it by making it easier.

    module DarkPower

    def crushTownsPeople

    end

    end

    class Jedi

    def drawSword

    end

    end

    class DarkJedi

    (i’m really hopinh your blog won’t screw up the indentation here …)

  4. I think I get the idea – mixins. Mixins are great things, but they are really a kind of multiple inheritance, and hence suffer from the same problems as I mention above.

    If you really must have all methods on a single object, Automated Delegation (google for “Automated Delegation is a Viable Alternative to Multiple Inheritance in Class Based Languages”) is the best bet – you can use the Strategy Pattern, but expose the component methods on the wrapping class.

  5. I think what you may want is the ability to pass store and invoke _functions_ rather than objects to express behaviour. In a language with first class functions (such as javascript but not Java) you don’t need the strategy pattern or the template pattern (and so on). I think you’d like is to use a functional programming language such as Haskell, Scheme or ..err.. Javascript.

  6. Good point David. Functions can be used in place of objects and it’s still the strategy pattern. This becomes more convenient with ActionScript or classes written in the MS Atlas framework, since this works:

    myAlgorithm.fooStrategy = new QuuxStrategy(3, 4).deliver;

    Where deliver() is a method that remains bound to its parent QuuxStrategy object. In this way you get the simplicity of passing in individual functions, and the flexibility of optionally using an object that can be configured.

    The reason I don’t do this in ActionScript is that you can’t enforce the type of a function with an interface. In C# you can, through delegates, which bring a whole new level of simplicity to component oriented development.

    As for functional languages, I’m waiting for web browsers to support LISP. Perhaps through some GWT-style translation.

  7. I tried something similar a while back, and string manipulation caused stack overflow errors due to its habit of mapping strings onto recursive linked lists of character nodes. Iterating over the string was done with a recursive function call for each character!

    I’ll have a look at this, thanks. What a way for in-house developers to make themselves indispensable: writing UI code in Scheme!

  8. Glad I found the place to comment. I was reading the article and thought, “how do I contact him?”

    I thought the article made good points and was generally sound advice, but I had a couple of questions I wanted to clear up.

    1) In the Jedi example, inheritance is still being used. You are simply aggregating dark powers within DarkJedi rather than putting them straight in. I think that’s fine, but was wondering if/how that contradicts what you were trying to show.

    2) I also was going to mention mixins or multiple inheritance, but since Evgeny and gs already did so, I’ll just ask about your response.

    In particular, you said:

    “multiple inheritance would have let you create a bouncing fading ball, but it wouldn’t have helped you in splitting the number generation strategy out into a separate class.”

    Of course, I agree here. But, I wanted to point out that it wouldn’t prevent you from doing so either. In fact, while you might be able to say bouncing is something all balls do (and include it in the ball class), I wouldn’t say fading is something all balls do. So having a FadingBall derive from Ball which then used the absSine strategy would make for a clearer object model in this case.

    Finally, you also mentioned you “think that while multiple inheritance eases the pain of inheritance a bit, it still encourages a ‘one object does everything’ style of development.”

    Do we really care if one /object/ does everything? Now, I definitely agree that one class should not do everything, but from the objects’ perspective, which is that of the running program, I wouldn’t think it matters.

    If an object calls theDarkJedi.crushTownsPeople(), it doesn’t care whether the code for crushTownsPeople() is included within DarkJedi or if DarkJedi simply uses another object for it.

    In other words, writing code in components is supposed to be for our benefit, not the program’s. Multiple inheritance / mixins seem to achieve that goal.

    It could be that I misunderstood what you were getting at with that comment, so feel free to rip into me. =) (ok, maybe not /rip/).

  9. All good points, I’ll address them one by one:

    1) Yes my contrived Jedi example contains an extends statement, so technically uses inheritance, but the important thing is that DarkJedi is now just a convenience constructor that wraps a Jedi and a DarkPowers. If you want to use inheritance to make convenience constructors, that’s fine, it’s putting the implementing code in the extending class that I object to, and that’s what 99% of people do when they extend a class. There are many other ways of combining Jedi and DarkPowers without extending Jedi.

    2) I gave Ball explicit yMotionStrategy and alphaStrategy properties to make the example clearer. In a real system you could have something more generic. For example, you could make a PropertyChangeStrategy class that holds a number of strategies and applies them to its containing object each frame:

    ball.strategies.addStrategy(“y”, new AbsSineStrategy(80, 200));

    ball.strategies.addStrategy(“alpha”, new AbsSineStrategy(0, 1));

    Now you can add the ability to make strategies that affect any property of any class by adding one line of code:

    public var strategies = new PropertyChangeStrategy(this);

    How cool is that?

    3) I guess you’re playing devil’s advocate here, but let’s have some fun anyway:o)

    MI still ‘bakes’ the behaviour into a class at compile time, and makes one big object with potential to have unforeseen interactions between the multiple base classes. It’s not that I don’t want an object with all those methods, its that I like to see functionality separated by object boundaries.

    I don’t deny that MI can achieve everything that the Strategy Pattern can (except runtime modification). However, the way to solve the tangled mess that inheritance leaves us with is not to make a super inheritance system that gives you more rope to hang yourself with.

    Problems with MI are well documented. Google for “multiple inheritance problems”. Consider that both Sun and Microsoft decided not to include MI in their virtual machines, meaning that no language that runs on that machine can support MI. C# gives you delegates, which really help the strategy pattern. I think that the language designers are moving away from MI as a way of enabling component driven development, now that people don’t care so much about the real benefit of MI – reducing the number of objects you instantiate and destroy.

  10. At OOAD level, inheritance represents “is-a”, as you said, at OOP you can implement it by delegation and interfaces. Inheritance in OOP is just an easier way to do it :-).

    And your last Jedi code example makes perfect sense, if you read the code, you clearly see:

    a DarkJedi is-a Jedi which has-a DarkPower

    If you suppress inheritance, you’ll have:

    a DarkJedi has-a Jedi and has-a DarkPower

    mmm… a DarkJedi has a Jedi inside?? wierd :-)

    Ok, let’s model it differently so it makes more sense, let’s have JediPower too:

    a DarkJedi has-a JediPower and has-a DarkPower

    Looks a little better, but is harder to model the fact that maybe someone has JediPower but is not a Jedi…

    There always alternatives and depends on what do you want to represent. The bottom line is with inheritance the pass from OOAD to OOP is more straightforward that without it (assuming you want to use OOAD, of course ;-) )

  11. That’s the problem with whimsical examples: since they are not doing real work in a real system, you can’t argue over exactly how to implement them, since the different implementations aren’t producing any results to compare. That’ll change next month when I come back with a real product.

    As for inheritance making OOAD easier, that’s only true because people learn OOAD as an exercise in mapping real world concepts onto an inheritance-based architecture. When you have been using the hammer of inheritance long enough, the world starts to look remarkably like the nail of hierarchical classification. Teach people to map the concepts onto interacting components, and I believe that they will learn to find the Strategy Pattern more intuitive than inheritance.

  12. But the example makes sense.

    Is the same as a CorporateCustomer is-a Customer or a Customer has-a CorporateInfo ?

    There’s no right or wrong, always depends on the point of view of your application.

    Probably the best explanation I can come is: if for your domain, the is-a relationship is invariant, better model it with inheritance otherwise use delegation. This forces you to provide a stronger justification when using inheritance (X is-a Y should be true *ALWAYS*).

    In my understanding, OOAD is about mapping concepts into interacting objects, not hierarchies.

    I agree that people get overenthusiastic about it and overuse is always bad (see what happening to patterns) and leads to this kind of backlash, but inheritance is useful :-)

  13. Firstly, good example; my argument is that Customer has-a CorporateRelationship is better.

    Here is one example of a real world problem that would be caused by forcing customer classification into inheritance: what happens when customer Dave Foo takes on a corporate relationship while the application is running? You already have an instance of Customer representing Dave live in the application. You need to restart the application to reload Dave as a CorporateCustomer.

    This is fine if you’re writing an HTML application in PHP, since the whole application restarts every request. It’s not so good if you’re writing an AJAX front end and a Java back end that both persist for a whole session.

    Secondly, the Strategy Pattern is just fine for invariant relationships.

    * It helps you write modular code that can be re-used in other places in your application (in the article, AbsSineStrategy was re-used for both kinds of ball, and could be used for wholly non ball related purposes elsewhere).

    * It maps better onto relational databases; much of the pain of object relational mapping is overcoming an impedance mismatch between relational schema and inheritance hierarchies that simply doesn’t exist if you use a component oriented architecture.

    * It makes it easier to write extremely generic code, such as the PropertyChangeStrategy in my example above. When the strategy is hidden behind an interface, you can write meta-strategies that wrap several other strategies, modifying or combining behaviour. Even if they are invariant, it still helps you compose behaviour.

    One can always come up with an example that looks like it would be better modelled with inheritance. My experience is that these examples are very rare in the kind of systems web developers build.

  14. Mmm I agree that Inheritance is often used in a bad way.

    Still there is a big difference between an “is-a” and a “has-a” relationship.

    The is-a relationship let you use polimorphism…

    At the beginning of your post, you say that you use Strategy Pattern INSTEAD OF Inheritance… But the Strategy Pattern IS Inheritance.

    The fact that java uses the keyword “implements” instead of “extends”, just because it doesn’t support multiple Inheritance does not change the fact that strategy pattern describes a “is-a” relationship.

    What you discovered here is just that the “is-a” relationship can’t solve all problems…

    Well thanks, but we already knew it :)

  15. > But the Strategy Pattern IS Inheritance

    No it’s not! Firstly, implementing an interface may count as inheritance in type theory, but “Concrete Class-based Inheritance is evil and must be destroyed” didn’t sound so catchy :o)

    Secondly, in duck-typed languages there is either no such thing as interfaces or they are optional, and the Strategy Pattern works fine in them. Clearly interfaces are not required for this pattern, and are incidental to the point I’m trying to make.

    > The is-a relationship let you use polymorphism

    No, polymorphism lets you use inheritance. Without polymorphism you would not be able to use a CorporateCustomer in place of a Customer, so inheritance would be useless. With the Strategy pattern you don’t need polymorphism, because there is only one Customer class, and that class may or may not have a CorporateRelationship.

    > Well thanks, but we already knew it :)

    “We”? You must be speaking on behalf of the exclusive club of web developers who bothered to read up on why design patterns matter and don’t just carry on hacking together systems using the first technique they were taught in college and shrugging off the resulting difficulties with an “oh well, software is hard” rather than re-appraising the way they do things. Can I join? I’ve been looking for you for ages!

  16. Ahh now I understand.

    I think I misunderstood what you mean exactly by Inheritance.

    >Secondly, in duck-typed languages there >is either no such thing as interfaces >or they are optional, and the Strategy >Pattern works fine in them.

    >Clearly interfaces are not required for >this pattern, and are incidental to the >point I’m trying to make.

    Ok, this is clear now

    >With the Strategy pattern you don’t >need polymorphism, because there is >only one Customer class, and that class >may or may not have a >CorporateRelationship.

    This is not clear. Assuming that for Stretegy Pattern you intend this: http://en.wikipedia.org/wiki/Strategy_pattern

    then the “execute” method is a virtual method. You have a pointer to a Strategy object and when you call “execute”, you are calling ConcreteStrategyA::execute OR ConcreteStrategyB::execute, depending of the type of the object your point is pointing at. And this is polymorfism as far as i know…

  17. I misunderstood, I was thinking of polymorphism as the ability to pass an instance of any subtype of class C to code expecting an instance of C. Since in type theory, implementing an interface creates a class that is a subtype of that interface, the strategy pattern does indeed use polymorphism.

    But, it replaces class-based polymorphism (CorporateCustomer can be used in place of Customer) with interface-based polymorphism (Customer has-a IRelationship, which might be a CorporateRelationship or a different kind of relationship). This is a good thing.

    Also, you could implement the Strategy Pattern without an interface. Customer could have a corporateRelationship property which is either null, or contains a CorporateRelationship object.

    Is that still the Strategy Pattern? Maybe I’ve used Strategy Pattern and component oriented architecture so interchangeably that I’ve forgotten the difference :o)

  18. I believe it’s for the reasons you outline in the article that a popular concept in OO design is to “favor composition over inheritance”–it makes systems more extensible and easier to maintain down the road.

  19. Hey Bernie, Excellent article, always good to see web developers with an interest in OOAD.

    I think my only comment would be that instead of citing the Strategy Pattern as the key to your discussion you should state you’re talking about composition versus inheritance.

    I tend to think of the strategy pattern as a way to provide different “algorithms” for a particular task. For instance the classic: providing sorting a collection with a different sorting strategy. It’s not something I’d think of for adding new completely functionality to a class to differentiate it from a super class.

    For instance, the in the Jedi example; I’d suggest all Jedis have powers, but the strategy provided for the powers class differs. DarkStrategy vs. LightStrategy.

    It does sound like, in that particular example at least, you’re really describing composition. Which would be how you would enhance a particular class in new ways, essentially enabling polymorphism in many situations without the resorting to inheritance.

    A good reference for this would be Bill Vener’s article on the subject.

    http://www.artima.com/designtechniques/compoinh.html

    I may be wrong though, I just see Strategy used a lot, and usually with good reason as it’s one of the most useful patterns.

    Thanks again.

  20. Nice article. It points out the problems with inheritance very well.

    I don’t agree with the notion of inheritance being evil and having to be destroyed, though. Like in your examples, your ball classes are extending MovieClip – a perfectly good reason to use inheritance. Well, considering all this, the title is probably just slightly exaggerated to gain more attention, which is good.

    Personally I find inheritance useful for creating base classes which perform certain tasks. One could argue, that you should use interfaces for this. If it’s something which almost always does the same task but in a slightly different way, I think it’s better to create a basic implementation and then extend the class, overriding some methods to perform the task in a different fashion. Use an interface, and you would have to write all the source code again.

    When you mentioned in the comments that the Customer class should have a CorporateRelationship, it made me think of databases: If you’re designing a database for customers, you wouldn’t chuck the relationship data in the customer table. In code, you might have the customer data loaded and then have the relationship loaded for the customers and added as a sub-object for each customer. If you had a CorporateCustomer class, you could in theory put the data for the relationship in the customer table, but it wouldn’t be very good practice in my opinion.

    Perhaps this kind of a view will help someone to look at their classes in a different way.

  21. I won’t disagree that inheritance is often the simplest way of implementing something. That’s the downfall of articles like mine – you aim to demonstrate a technique that helps manage complexity, and in order to stay under 20 lines the examples you use don’t require that technique.

    However, in real systems, I find class-based inheritance bites me in the ass even when I thought it wouldn’t.

    > Personally I find inheritance useful for creating base

    > classes which perform certain tasks

    Sometimes the simplest way to allow users to extend your system is to provide a class with many methods, each of which provides a default action, and allow users to selectively override them. I grudgingly allow this advantage :o) It’s still the wrong way to do it, for the reasons outlined in the article, but when ease of use for programmers of varying skill is the main concern, the benefits beat the downsides.

    > If you’re designing a database for customers, you

    > wouldn’t chuck the relationship data in the customer table

    Of course not, you would have a CUSTOMER table, then a RELATIONSHIP table, and either a customer_id on RELATIONSHIP or a CUSTOMER_RELATIONSHIP link table. Spitting Customer and Relationship into two different classes makes this mapping intuitive: one class per table. Extending Customer with CorporateCustomer means that you have to join the two tables together and put the data into a single object. This makes it very difficult to refactor to change the cardinality (one-to-on-, one-to-many etc) of the table relationship.

  22. > Spitting Customer and Relationship into two different classes makes this mapping intuitive: one class per table

    >Extending Customer with CorporateCustomer means that you have to join the two tables together and put the data into a single object.

    Which is why looking at the problem from this point of view can be helpful for figuring out a better approach than inheritance.

  23. “These classes obviously can’t extend Jedi, so you have to duplicate townspeople crushing functionality across your whole DarkArmy or split it out into utility functions that you call from every crushTownspeople method. Either way, it gets complicated.”

    How created further in the article the DarkPowers class is different form a utility class?

  24. Arte: If calling code expects the crushTownspeople() method to exist on the DarkJedi object itself, then even after moving it to a utility method you still need a stub method like so:

    public function crushTownspeople():void {

    DarkUtils.crushTownspeople(this);

    }

    If calling code expects it to be in a darkPowers property, you don’t have this extra boilerplate code, just:

    public var darkPowers = new DarkPowers(this);

    Sure there’s not much difference with just one method, but if there are 10 dark methods it becomes a pain in the ass to write and maintain the stubs. Also, if you add another dark method, the first version forces you to update every dark class, whereas i the second version the extra method is acquired by every class with a darkPowers property.

  25. You should take a look at Fragment Oriented Programming (short FOP). With FOP you simply compose your classes from fragments.

    The animated Ball examples could look like this

    The Fragments for Ball could be StaticColor, StaticPosition and DrawBall

    The Fragments for BouncingBall could be StaticColor, Bouncing and DrawBall

    The Fragments for FadingBall could be FadingColor, StaticPosition and DrawBall

    and if you want to compose a FadingBouncingBall or even a TextureFadingBouncingBall you simply use different Fragments.

    There is an implementation of FOP available for C++: http://fragments.wiki.sourceforge.net/

  26. That sounds like a very clever solution to a very real problem, except for the fact that I will never program in C++

    They can pry the dynamic languages from my cold, dead fingers :o)

  27. Hey Bernie,

    I think you are right in many regards and you are defiantly on the right track, however I feel your example is slightly off.

    If you consider the Liskov Substitution Principle (LSP) and the Open Closed Principle (OCP) you will see that the CrushTownPeople() method violates them.

    If we consider what happens with different kinds of Jedi interact with towns people; Good Jedi would HelpTownsPeople(), and if you had a grey jedi it would BeIndifferentToTownsPeople()

    So the code that had jedi’s interacting with towns people would not be very polymorphic and would need to know about all the different kinds of jedi.

    For more on the subject i suggest reading:

    http://www.objectmentor.com/resources/articles/lsp.pdf

    Hope this helps.

  28. Was the comment intended as a note on the Star Wars universe or the principles of Object Oriented Analysis and Design?

    If the former, then quite so: good Jedi would no doubt help townspeople.

    If the latter then the LSP becomes irrelevant when you design a system without inheritance. The LSP is concerned with how you model a system of many related objects using inheritance. I am concerned with how you model a system of many related objects without using inheritance!

    The whole point of using composition over inheritance is that you don’t substitute one object for one of its subclasses, you always pass in that object and its behaviour will depend on its composition.

    If we were to model GoodJedis and GreyJedis (do they exist?) then we would have a public property townsPeopleReaction, which would contain an instance of CrushReaction, IgnoreReaction or ProtectReaction.

    Either way, a plain Jedi object is passed to the townspeople, and not a subclass. Liskov be damned.

  29. Interestingly, while I don’t disagree with any of your points, I still disagree with your main argument. I think you have done a great job of showing the problems that arise from using an “is-a” relationship rather than a “has-a” relationship. Even in your contrived example, it makes sense that a DarkJedi *has* DarkPowers, but for all that, it still *is* a Jedi. Of course, “Inheritance is overused, and often has better alternatives” isn’t nearly so catchy of a title.

    And while JavaScript’s inheritance may seem like a pain to those who have been perverted by class based languages, I think it is actually much more powerful, and much easier to use. (My one complaint is the awkwardness of doing something like constructor chaining.) It give you a much wider range of options than class based languages. First of all, as you stated, because JavaScript is not a strongly typed language, it doesn’t force you to use inheritance just so you can fill in for an existing type. Moreover, for one-off cases, you can add methods to an existing object without changing it’s definition, something that is impossible in many class based languages, and also eliminates another common source of people using inheritance where it shouldn’t be. I have seen much evil done by Java programmers new to JavaScript on account of these two points alone. But beyond that, JavaScript’s prototype system allows for much more powerful techniques, such as Ruby-style mixins, or multiple inheritance, including selective, or “Swiss” multiple inheritance, which also works around many of the common problems with multiple inheritance.

    Of course for people who are stuck in strict classical OO languages, I can understand your point. I’ve recently switched from programming mostly in JavaScript to programming mostly in PHP, and I am really missing a lot of JavaScript’s flexibility.

  30. An interesting point – I was thinking about class-based languages when I wrote the piece.

    JavaScript is a special case, since in JavaScript, *every method* is already a Strategy. In JavaScript you can choose to swap out any method at runtime, dynamically build new classes, or modify the prototype of existing classes for AOP effects. In short, far from not requiring the pattern I suggest in this article, JavaScript implements it by default. I would argue that since the Strategy pattern is already so well supported in JavaScript, that’s extra reason not to resort to MI and mixins.

    Here’s an example – supposing you are building an object that at some point needs to alter the value of a string in a way that the user of the class wants to control. You can provide the string editing as a Strategy or a mixin.

    A nice trick in JavaScript is to provide a default Strategy function ‘this.stringEditor(str)’ and whenever you call it, use the code ‘this.stringEditor.call(this, str)’, i.e. by using the ‘call’ method that exists on all function objects. If client code needs to supply new string editing behaviour, they can write a new function and replace the existing ‘this.stringEditor’ on a per-object basis or for a whole class using the prototype. If the bit of behaviour is more complex (e.g. it has multiple configuration options and helper functions) then ‘this.stringEditor’ can be replaced with an object that contains a ‘call(parent, str)’ method. This lightweight Strategy pattern lets you get all the benefit of Strategy objects, without the overhead when you’re not using them.

    Now consider if you’d used a mixin. In the simple case of one function editString, it’s fine. When your mixin starts needing complex state and helper functions, these pollute the object’s namespace and make it difficult or impossible to change the Strategy at runtime.

    That said, some JavaScript frameworks make great use of mixins for providing core functionality to classes. Prototype’s Enumerable mixin is a perfect example. It is so successful because it is providing core functionality to an object, and there is no way you’d want to change the way an object Enumerates its children at runtime.

  31. Thanks for the awesome article. Really thorough. Well done!

    I think I don’t understand the following statement correctly:

    “If you need to make a DarkDroid and a DarkSpaceship that can both also crush townspeople, you’re in trouble.”

    Surely, DarkDroid and DarkSpaceship can just inherit from DarkJedi? They will then get the same functionality to crushTownspeople() and still be a DarkJedi & in turn a Jedi?

    What am I missing?

  32. Good article about “inheritance is evil”.

    The software gods at our educational institutions are certainly not happy with you but every you said in your article is true.

    The software world would be a better place is inheritance never was introduced.

    Seems to me that encapsulation and inheritance are mortal enemies. I suspect a committee was involved in this terrible mess.

    Complexity…Complexity…Complexity…

    KISS-Keep it simple stupid.

    Who ever conjured up inheritance should be beaten with a “KISS” stick.

    Kevin McLaughlin

  33. Have you ever had a look at Sather? It is a programming language, with inheritance, but only interfaces can inherit from other interfaces. Classes implement interfaces and classes cannot inherit of each other. There is no “implementation” inheritance in Sather. A class can only consist out of other classes and the compiler can automatically let you forward messages sent to your class to any of those internal classes (basically it generates the necessary code to dispatch messages to internal objects for you based on a set of rules you write). And you pass classes around either as the class itself or by its interface of course.

    http://www.icsi.berkeley.edu/~sather/

    Sather is no interpreted language. The Sather compiler translates your Sather code to plain-C code that can then pass through GCC to get native code in the end.

    One drawback of Sather is, that it does everything at compile time, never at runtime, so any change to the inheritance system, to classes or classes-within-classes force a recompilation of the whole thing. Therefor it runs at native speed, not much slower than plain-C would be, if it used only indirect function calling (passing functions around as pointers and calling them that way) – which is still faster than method dispatch in many other languages.

  34. Although I like the article and have cited it when I needed support for declaring that implementation inheritance is not a good thing, I still feel the need to point out that the dark powers example could be solved quite elegantly with multiple inheritance, as C++ has. Even the problem with the EventDispatcher would disappear.

    Perhaps you could shed some light on your view regarding inheritance in a world where multiple inheritance is allowed?

  35. @Michael Piefel: my position on multiple concrete inheritance is that it solves the main problem with single concrete inheritance, but creates complexity problems. In particular, constructor chaining becomes complicated when you inherit form multiple classes.

    My preferred flavour of MI is the mixin – a unit of functionality that can be added to a class. A mixin-based MI system allows you to inherit from one concrete class only, and any number of mixin classes. Mixins can’t have multiple constructors, so chaining is not an issue.

    I’ve made such a mixin system for Java that uses runtime bytecode generation to implement mixins via automated delegation: http://berniesumption.com/software/mixins-for-java/

  36. Nice article. I am new to javascript but come from an OO Perl background and I have already discovered and agree with your findings. Nice to see I am not alone:)

  37. Bernie, nice article.

    I tend to agree with you. I think the Decorator pattern specifically addresses the case against inheritance in UI design; it follows your rationale.

    And in most part I find that once an inheritance solution is adopted, you almost find cases where it needs to be broken and pulled apart (or most likely reduced to Interfaces).

    However inheritance can resolve issues around tight coupling and dependencies between objects, it just needs to be used judiciously.

  38. The problem isn’t with inheritance, its the lack of multiple inheritance (C++ is awesome btw) in all of the new languages that only allow single inheritance, which I wish I knew why this decision is being made with new languages. Interfaces seem like a very flimsy piece of tape to get around this issue. Interfaces aren’t even nessisary when multiple inheritance is present.

      1. google “forest of trees pattern” or “capability classes and queries pattern”….there are solutions for the dreaded diamond

    1. C++ is NOT awesome. I’m sure most C++ programmers with a clue would prefer to be coding C but were forced into OO compliance by some buzzword-loving management a55holes. Linux Torvalds is a seriously talented programmer and publicly loathes C++, as do countless others.

      Not only is classical inheritance a f*cking stupid idea but to make things worse, the way C++ implements it is by far the worst of the bunch.

      You are a cargo cultist of the worst kind.

      1. In all fairness, I think that the *worst* kind of cargo cultist would be one that killed kittens or something. Or parked on double yellow lines.

        (Gasp!) or maybe killed kittens while parked on double yellow lines.

      2. Scott Meyers is a seriously talented programmer and publicly loves C++, as do countless others…

  39. I’m not convinced. Seems to me inheritance is a tool. Like any other tool, if you use it incorrectly it cause problems.

    However, your article will cause me to reflect on my uses of inheritance.

  40. @Jason: You’re right of course, but the Internet seems to prefer bombastic one-sided proclamations to nuanced accounts of pros and cons ;o)

  41. This all makes sense except all your examples still use inheritance. Kind of a let down after the hyperbolic title. :-)

  42. Inheritance is God when it is used correctly is wonderful, otherwise is only a mistake.

    For example. The truth is your example of inheritance is an example of the use of interfaces. Your example is the same thing to sell guns to American people. They could bought but they don’t know used.

    So sorry You’re wrong!

    1. unfortunately, programmers ain’t gods

      pulling my hair ATM not because I’m using inheritance inappropriately (I do understand what “is-a” relationship means), but because requirements and object responsibilities have changed over time.

      inheritance would be awesome if I could time travel and figure out requirements perfectly.

      1. I think that the problem lies with us trying to create largest possible classes while we should be designing smallest possible class. For example in C, I would put two functionalities in a function only if I am sure that I would never use them separately. Rather than keeping two functionalities separate only when I know of their usages separately.
        That is how we tackle future needs, because the problem is independent of inheritance.

  43. Excellent post! I completely agree with you. Inheritance is the wrong tool for code-reuse. Unfortunately, in mainstream languages, there’s no better tool, so it gets really really abused. Take a look at traits, you’ll like them…

    1. I rate if used wrong you won’t be able to reuse. However in alot of instances especially in PHP and C++ i find it extremely time saving for larger projects to use inheritance. But as mentioned here it depends what the super class function is.

      For instance, say I’m implementing a pluginable cart checkout process. You have different types of Payment Gateways. Each payment gateway has a CheckOutURL(), a Description(), a Title() etc etc. That’s for the PHP side of things.

      In c++ the best usage could be thought of in a game. Both NPC’s and Players are renderable, can be controlled (by keyboard or AI module), have a position, orientation, and animation states. To reimplement these for all different types of NPC’s and Players is just code bloat and highly unoptimal.

      In the example of this page the DarkJedi example is the perfect example how NOT to use inheritance. DarkJedi is a jedi who is also dark inclined. Therefore I would say Jedi extends both Jedi and DarkEntity (DarkEntity being an abstract for entity that has dark inclinations) .. Therefore a DarkHippo is a DarkEntity and a DarkJedi is a dark entity. In which case both DarkHippo and DarkJedi’s crushTownsPeople(), but only Jedi’s can use the force to do so. The only time this would make sense to use would be if suddenly a normal Jedi wanted to kill off all DarkEntities regardless whether its a Jedi or a Hippo. etc etc.

      It obviously depends on your ability to use the language feature to long term advantage which is why inheritance heirachies should not be created at whim but rather planned out in advance using spider diagrams or inheritance trees. Stipulating exactly what a class does thats so much like its parent, and whether the class is infact the parent. Just because the class has the same functions doesn’t mean it is the same thing. Just because you can drive a Boat doesn’t make it a Car, but they are both Vehicles. You won’t take a boat to a car Mechanic so don’t send Vehicles to mechanics, etc etc

  44. Good article. It’s always helpful and interesting when someone share experience about those kind of development aspects. I don’t think inheritance is the problem because these choices are related to design. This is why GOF has imagine pattern like Strategy, Command, Observer and others.
    But developer needs to determine which one to use : That is answering correctly to Do I need an “is-a” or an “has-a” like “is-composed-of” etc…etc… ?
    Multiple inheritance like in C++ may be useful but is not a good idea because it can lead to an ugly or more complicated design than it should be (e.g : When overriding methods…)

  45. But you’re right inheritance is often overused without relfexions…may be there’s some kind of human automatic reflex there :)

  46. In your example clearly Darkness belongs in another class.

    Theoretically you could use multiple inheritance for this (if your language supports it). But then you have the diamond problem.

    The diamond problem comes from function overriding. Although inheritance is meant to implement “is a” relationship in fact this is not strictly true.

    Classes may be related set theory. A class is a set. When we say Dog Inherits Animal, we mean the Dog set is a subset of the Animal set.

    Now say we have a rule “all dogs chase cats”.
    dog.See(cat) implies dog.Chase(cat)

    This could be written as a method,

    void Dog.See(Cat cat)
    {
    Chase(cat);
    }

    Now suppose we have a class CatLovingDog that inherits from Dog.

    void CatLovingDog.See(Cat cat)
    {
    Greet(cat);
    }

    This is an exception to the rule that “all dogs chase cats”. So function overrides are a weird cludge exception mechanism, which doesn’t even work for multiple inheritance (the diamond problem). A correct logical interpretation would be that when you call See(cat) on a CatLovingDog you get both implementations.

    The diamond problem has lead people to adopt single inheritance, which makes as much sense as saying an object may only belong to one set.

    There is another problem in that the return type is not part of the signature in most languages. This is evil because you can’t change the return type on an inherited method.

    To summarize, most programming languages do not correctly implement set theory, and are very sick. This is why you are against inheritance. I have seen nothing in your arguments to show that a correctly implemented multiple inheritance system would have any problems at all.

    The goal is always single purpose small classes.

  47. IT IS NOT A BALL IT IS A CIRCLE! (new Sprite ().graphics.drawCircle())
    Calling it a FadingBall is a mistake like saying YourMotherInClothes extends YourMother.
    I have one shape class that can be anything from Circle to Rectangle by encapsulating a style object.

    Consider using a Tweener for your animation.

      1. You touched something, that I’d call religious believing.

        Once I wrote on StackOverflow, that inheritance isn’t all OOP is about, I got several down votes.

        Brad Cox (co-creator of Objective-C) was interviewed for the book “Masterminds in Programming”. He was asked, why Objective-C doesn’t have multiple inheritance.

        Answer: “[…] If I revisited that decision today, I might even go so far as to remove single inheritance as well. Inheritance just isn’t all that important. Encapsulation is OOP’s lasting contribution.” (Masterminds of Programming: Conversations with the Creators of Major Programming Languages, p. 259)

        One thing, you will always hear about sub-classing is, that you are dealing with black-boxes — that you would deal with objects you don’t have to know about how they look internally. But that is just not true: It is white boxing, as the subclass knows the internals of the superclass — and the author of the subclass needs to know these internals too, otherwise he will most likely have unexpected behavior if he accidentally overwrites members of the superclass.
        Real black boxing can be achieved by object composition.

  48. @Bernie

    If you really want to make your case, I think you should take a classic is-a relationship, like your R2Unit > Droid example, and rearticulate that into a has-a relationship. How is it logical or useful to say that an R2Unit “has a” Droid?

    1. The has-a relationship makes sense because the Droid class does not represent a noun, it represents characteristics and behaviors. Therefore the R2unit “has” Droid characteristics and behaviors.

      It’s those characteristics that make it a droid, not because we say it is, but because it looks and acts like one.

  49. Somewhere inside that article is a good and valid point about when it is and isn’t appropriate to extend. But by starting your article with “bombastic one-sided proclamations,” you immediately hurt your credibility. You’ll appeal to the zealots who agree with your one-sided proclamation, but you won’t gain any respect from the good programmers who understand the nuances of inheritance.

    1. Of course I have no credibility. Credibility is something you have or don’t have when you are debating important topics with real outcomes. Architectural discussions in a real product for example. This post is just a little bit of thought-provoking fun :o)

  50. I hate to be the only voice of Ruby in this thread, but I should let you know that one of the significant features of Ruby is that it is object oriented but it doesn’t have multiple inheritance, it shares implementations across an inheritance tree. Very similar to the Mix-in stuff I saw on your code page. Considering your background in Java and how much it looks like you’re enjoying Javascript interpreters, you might actually love Ruby, as it’s like java but executed as an interpreted language and without the need to compile and without the class inbreeding of evil inheritance. Ruby and Javascript function the way your post eludes other languages should.

    Though I’m not sure the world is over how “cool” it was when it was the new guy. So I disclaim that I myself am a broad-facing-actor zealot. I Iove processing & processing.js right now, I’m inspired by openframeworks and I wonder when the world is going to really use RDFXML for something useful.

  51. Every article on this subject always states that inheritance is bad, and then goes ahead to prove it by showing some examples of the bad use of inheritance? Anything useful can be used badly – give me a hammer and I’ll prove it.
    As many people have said, use it correctly and it’s wonderful. Your jedi example fails because DarkPowers are, by definition, something that a Jedi “has”. This is your first clue not to use inheritance in this example. What’s more, if DarkHippo ever took it upon himself to use a lightsabre, he wouldn’t be able to, because DrawSabre is “locked up” in the Jedi class. Are you going to put every method you define in it’s own class? Obviously not.
    You can’t prove that “is-a” relationships are bad by using them to model what should be “has-a” relationships, and then blowing the example apart. Use inheritance properly, understand what you’re doing, and there’s no problem.

    1. Do you have an example that you would like to share where single inheritance is significantly more useful than has-a type implementations? I am genuinely interested.

        1. Yes, and yes.. :)

          It’s interesting that although this pattern is a very good case for inheritance, it still can be substituted for a more general interface, albeit at a bit of a cost as you mention. I suppose what I’m wondering (from the viewpoint of any taker) is: does this pattern warrant the use of inheritance, or can it be safely avoided with a wee bit of pain in very specific circumstances? I’m guessing the latter.

          I’ve felt very similarly to the sentiment of the article title. It seems that I’m always trying to fit my code into the inheritance structure, rather than having it work for me. In fact, the majority of my code that doesn’t rely on environment specific classes, but tends to consist of shallow objects.

  52. Hey guys, you should really look at what happens when functional elements are included in a language, such as in C# with extension methods. If you keep the “is-a” heirarchy smoothly supported by inheritance (as is its proper purpose), you can then still extend objects with functionality by adding extension methods. If combined with interfaces (blank, or just providing the required properties and methods) then you can mark an object as inheriting an interface and then extend that interface to add methods to all grouped objects. This can even be inserted from other assemblies, so black-boxed OO classes are still accessible for extension and effective duck-typing. You can always combine this by having a simple implementation that routes methods to a child object, so the interface define the child object, whilst a child object provides the implementations. This appears to provide a more complete range of solutions to suit all potentials than the limited set discussed here.

  53. The “is-a” / “has-a” way of seeing things is OK, but to me it doesn’t explain what inheritance – and its “complement”: composition – is really meant for (at least, to me).
    Inheritance allows you to specialize.
    For instance: given your base class A implementing a few methods, you may (and certainly will) get to a point where A almost fits your needs, but for some (local) business logic reason, you’d need some of A’s methods to behave a bit (or completely) differently.
    You could actually add more specific methods to A to fill the “gap”, but doing so, you’d just end up with a huge class full of methods that would be used in certain occasions only, which would be hard to maintain (and quite a naive approach).
    You could also copy A, and turn it into another class B, then change the methods implementation where needed. This is OK (and quite logical) if you actually have to alter all the methods (which would imply that you’d actually need another, different class from A – and then inheritance would not be useful at all, even for “is-a” sort-of classification of classes). But if you really need say 95% of A, thus changing just 5% of it in B, you’ll end up with 95% code duplication (which is, again, not a good idea).

    So, this is where inheritance is useful: it will help you specialize your B class by changing methods that need to behave differently but still benefiting from A’s methods that are the same. So, B (and all possible other children classes), will be similar to A in terms of “what they are” (properties and methods), but will differ in terms of “what they do” (methods implementation will be more specific in the children).
    If you keep that in mind, you’ll use inheritance for what it is meant to do, thus will use it the right way and when needed only.
    Quite a few developpers actually use inheritance with abstract classes only (and I tend to do so myself though not systematic): they just implement the methods that won’t require changes in the children, leaving the other ones empty (for future, specific, specialized implementation right into the children).

    Now: inheritance is NOT meant to ADD things that don’t exist in the parent! This is, to me, a terminlogy issue with the term “extends”: you actually don’t extend anything with inheritance, in terms of new functionnalities, you just specialize (again, again, again…) the existing ones. If, beside specialization, you need to extend (ADD) functionnalities, then inheritance is not the good “tool” for this. Of course, you can do it, but this is that nice: what if the portion of code you add to B (child of A), is also required in its “sibling classes” C, D, K, P? Will you duplicate it? Hum.

    To add new things, you’d better go with composition: put the “new” code elsewhere, in another class, then call it where needed in your specialized methods. Doing so will keep all your parented classes consistent AND will avoid code duplication (right now and/or in the future) whenever you need to add the same functionnalities in different places/classes (parented or not). The strategy pattern, cited in this article, is an interesting way of doing composition, and you should use it when it fits the needs. Of course, the use of design patterns must always be relevant to the actual need or problem, and not a systematic behaviour nor dicted by hype.

    1. I see your point. However:

      a) if the designer of the base class did not intend the methods to be overridden, then overriding them may create random odd bugs, but b) if the designer did intend the methods to be overridden, then they could just as easily define a strategy interface that you can use to pass in an object representing your intended customisations.

      1. Hi Bernie
        Thanks for your reply on this.
        Well, I see your point too. Here are my thoughts.

        a) if the designer of the base class did not intend the methods to be overridden, then overriding them may create random odd bugs,

        Well, as for OOP “standards”, if you don’t explicitly “tell” that your methods must not be overwritten, you implicitly admit than they can, thus will certainly will, at some point.
        So, if you know that this or this method should not be overwritten in children classes, then you have to do something accordingly. Making the method “private” will prevent overwriting (at least in Java, and PHP, as far as I know), but this will also prevent sub-classes to actually use it directly. This is when the “final” keyword comes in handy: it doesn’t tell who can use the method (like public, protected, private do), but that it must not me overwritten elsewhere. Don’t know how many common OOP-enabled have the “final” keyword, but you should use it wherever it is identified that the method should not be overwritten (ie. a Singleton base class, for instance).
        It is within the “main” designer to think that out, to anticipate the use that will be made of their classes, so you have to be careful about that, and protect/hide attributes and methods that should stay unaltered, for example.

        but b) if the designer did intend the methods to be overridden, then they could just as easily define a strategy interface that you can use to pass in an object representing your intended customisations.

        “just as easily”, I’m not sure. Be careful with patterns, I mean: be clear with yourself about what they have been invented, tested, and approved for, and what you could potentially use them for. This is comlpetely different, and very often leads to misuse.
        Keep in mind that the Strategy pattern is a form of IoC, first. And as every other pattern, it should be use to solve the problem it had been designed to solve, solely, when identified.
        What is Strategy meant for? Very basically, and to turn it short, you can convoque the Strategy pattern as soon as you’re noticing that this class “knows or assumes or does to many things regargind what it’s being developed for”. It’s important to keep in mind that if the Strategy pattern, as an IoC pattern, does loosen coupling, it also brings some more overhead as you’ll have to instanciate and pass other objects then. Which meand that if you do this all the time, your application will do too many things even for simple tasks. Again, using patterns (and even less this or that pattern precisely) are not a panacea, they do well for very specific problems.

        Now, imagine a (PHP) class “A” (again ^^), defining base methods, amongst which a very, very, basic one: [public] __toString(). And let’s say that you want it to be a bit more precise than just outputting “__CLASS__” (which, by the way, may be a problem in subclasses if you don’t use Relection or late static bindings), for instance “Class A object. Base class to handle this and that. Can be inherited”.

        Classes B, C, D, E, F are children class. Specializing the toString() method in each subclass is very easy, and will cause no specific overhead.
        Now imagine it via the Strategy pattern. Tough.

        Even worse if, instead of this simple, always specific method, you only have one or two functions amongst say 6 or 10 that will really require specialization: you’ll convoke the Strategy pattern for all cases, even those that are always the same and not likely to change…

        Really, I don’t think you can use Strategy where inheritance is the best answer. Call it where you need composition, say where you need not to specialize your classes but to add functionalities to them: this will be a real case where Strategy (and more generically, IoC), will be at its best use. I recently found on the web a pretty good Strategy example on a search engine (sort of) class. Whet it came to sorting, the developper felt that it had no real binding to searching, actually (and to me he was right). This was a typical case of both problems: “this class will need to know/do to more than it has on its own”, and “I may need sorting functionnality elsewhere in my application, not just into my search engine” => then, he pulled the sorting stuff out of the SE class, coded a sorting class, then was able to use the Strategy pattern to use it within its SE (or whatever). The big plus: whenever he needs a new way of sorting things, will be very easy, and he’ll need not to alter he’s SE code. Clearly (at least to me), this is when IoC patterns should be used.

      2. Hi Bernie,
        I feel a bit like a spammer right now ^^
        Speak so much that I forgot to mention something interesting (and important) as of patterns and inheritance: the Deocorator pattern.
        Basically, it is sort of a substitute for sub-classing, but it should be used in some specific occasions only (as always with patterns).
        Say: if the (modified) behavior has to to be added/removed at run time, or if you need to combine the functionalities from multiple decorators (where multiple inheritance is not possible, like in PHP, or not suitable nor wishable)

  54. Sounds like the problem is a lack of Interfaces. DarkJediPowers should be an interface that anyone can implement.

    Your Ball example actually works equally well with this!

    Interfaces when all implementations are best represented using multiple inheritance of course. Then again in my experience it is rare that a DarkHippo is going to crush villagers in the same way a DarkJedi will. :)

  55. I’m relieved that I’m not alone with my view of disliking inheritance.
    And yes my main problem with it is that it’s against encapsulation as sy already wrote (I just couldn’t name the feeling).

  56. ———————————————————————-
    To: thpigdog
    ———————————————————————-
    Now say we have a rule “all dogs chase cats”.
    dog.See(cat) implies dog.Chase(cat)

    This could be written as a method,

    void Dog.See(Cat cat)
    {
    Chase(cat);
    }

    Now suppose we have a class CatLovingDog that inherits from Dog.

    void CatLovingDog.See(Cat cat)
    {
    Greet(cat);
    }
    ———————————————————————-

    No, rather than creating “some other kind of dog”, (the same fundamental inheritance problem discussed in the article), instead the thing to do is to modify the existing dog definition by adding a “CatAffinity” property.

    void Dog.See(Cat cat)
    {
    if (this.CatAffinity > 0)
    Greet(cat);
    else
    Chase(cat);
    }

    Chase or greet is not an “is-a”, nor is it a “has-a”. Instead it’s an attribute of a specific instance.

  57. C++ multiple inheritance works great! The classic diamond problem is solved by the compiler mentioning the ambiguity of your code. I have bent over backwards trying to find a work around to not having multiple inheritance in C# (or same thing with Java, AS3). The best I can do is create an interface of the second class I want to derive from and, eeeeeeeeewwwwww, copy and paste the implementations of its methods. Such a shame. I blame Java for this. Correct me if im wrong but they are the bastards that started the whole interface thing.

  58. Pink at the top of the page template is eye bleeding (#ff0080). The bottom color of the gradient (#b3002d) goes nice with the textured grey.

    1. I disagree. #FF0080 (DEEP PINK, FUCHSIA) is the greatest of all the colours. Your eyes only bleed if they aren’t awesome enough to handle all that pink!

  59. Google GWT has an hybrid approch :

    interface IsXxx {
    Xxx asXxx();
    }

    Yes, you have to copy/paste the Xxx field declaration and this declared getter, but that’s all.
    You are free to respect this IsXxx contract by either inheritance or aggregation.
    (Even you are no more concerned by method name collision)

    Meanwhile, C++ multi-inheritance provides two facilities:
    – you don not have to { cast as Xxx / use xxx field / use asXxx getter }
    – child classes have access to parent’s protected members

    Actually i think the mostly used of inherintance is to simplify a composition.
    By exemple, if to make a X you need a common B and custom C
    with inheritence: X/B are base, C extends X/B
    with agregation: X is interface, B and C classes, C’ assemble B and C to become a X
    and you need extra interfaces to define communication between B and C, and the rest of the world…

    Finally I agree: inheritence is bad, but a shortcut.

  60. dont know if some1 pointed it before, but this topic is a “inheritance versus composition” dilema.

    Inheritance isnt evil neither is composition, they just are tools/techniques and you have to use them wisely in your design. (thats why you have to think about your design instead of start writting code and doing iterations in a backstracking (test and error way)

    “is-a”: inheritance
    “has-a”: composition

    lets imagine this 2 classes:
    public abstract class Horse extends BaseLifeForm.
    public abstract class Truck extends BaseMachine.

    this is making an asumption: machines will never be a life form, so you have 2 hierarchies: lifeforms and machines. ¿but what if some day artificial intelligence makes possible that machines became a form of life? UPS!
    anyways: horses will never have a “turn on” method…. ¿or not?

    at the end, its all about making a design based in some scenario.

    disclaimer: english is not my native language so dont blame my mistakes :)

Comments are closed.