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.
GoodIn 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. |
BadIn 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:
- You can change the behaviour of each ball at runtime: a bouncing ball can become a fading ball at any time.
- 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.
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.

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.
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.
> 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.
“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?
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.
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/
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)
Hi there,
Heads on! I’ve been suspecting something like this, but not been able to formalize it. Thank you!
Qi4J, http://www.qi4j.org/ formalizes this thought in the Java world, well worth a look!
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.
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.
your code examples are well formated and clear enough to convince me! ;D
Sounds like you might find Scala traits interesting:
http://www.scala-lang.org/intro/traits.html
You can add them to instances too:
val q1 = new StandardQueue with LockingQueue with LoggingQueue
where LockingQueue and LoggingQueue are Traits (example from the scala book).
Just a thought.
Thanks. This is a very good explanation of the problems of inheritance and a good introduction to composition.
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.
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.
check out Joose
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?
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
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.
Pingback: Inheritance is evil | (blog-of "Alex Shabanov")
Pingback: Why Inheritance is sometimes Evil | Savetime On
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?
@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/
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:)
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.