*Note to our gentle readers: This is one of those blog entries that probably raises more issues than it resolves. Further, it requests reader input. Consider yourself forewarned.
Why Polymorphism?
As just about everybody reading this blog knows, polymorphism is a foundational concept in object oriented programming (OOP). We devote several pages to polymorphism in our introductory chapter showing what it can do and what it looks like using several examples. (In fact I think we did a pretty decent job) However, I still don’t have the same kind of intuitive sense for polymorphism as I do for encapsulation, inheritance and some of the other concepts that make up OOP and more importantly, design patterns.
I went to my bookcase and found lots of discussion of polymorphism, and on the Web I found lots more. What’s missing (for me at least) is a visceral connection between polymorphism and design patterns. We can all talk about overloading methods, using interfaces to achieve polymorphism and provide all sorts of examples. But that’s not the same thing as smoothly working in polymorphism as a thought pattern when programming. I wondered if anyone else had the same minor intellectual itch that I do, and lo and behold in the Wikipedia entry on type polymorphism I found the following note:
All or part of this article may be confusing or unclear.
Such a notice is another way of saying it doesn’t make a lick of sense. This is not to say that the explanation is inaccurate. Technically, it’s very accurate as far as I could see. It’s just not very clear.
Searching further, I found more confusion about polymorphism. On one Java blog, a participant asked about the different kinds of polymorphism, and another responded that there was only one kind. However, you can quickly find lots of type referenced polymorphism, but whether the different kinds are important to OOP or not is muddled.
How Can You Confuse a Pointer? Easy!!
An important feature of understanding polymorphism is understanding pointers. Well, I’ve never had a problem with pointers (or so I thought) until I came across this line in some university notes,
Some people claim that Java has no pointers… Not true!
All objects are accessed through references, which are automatically de-referenced pointers
Right after I read that, my brain caught on fire and smoke billowed out of what’s left of the hair on my head. “What the…?” First, I wanted to know who those people were who claimed that Java has no pointers, and second what do the same people think about pointers in ActionScript 3.0. (Maybe I’ll just gather up my de-referenced pointers and go play solitaire.) Okay, so we need clarification on pointers.
All exasperation aside, none other than Sun says that Java has no pointers. What do they mean by that? On the other hand, the Flex ActionScript 3.0 docs indicate that,
An object may contain pointers to other objects that themselves contain pointers to even more objects.
Oddly, that makes perfect sense to me, but what ActionScript 3.0 has by way of pointers that Java does not have is a bit confusing. Why should I care? (Or why should you care?) Here’s why: A lot of the discussions about polymorphism make a reference to pointers, and many of those discussions are in Java contexts. So you see in the Java articles, “blah, blah, blah, pointers, blah, blah, polymorphism…” and up comes the big question mark and “What the…?” How can Java programmers talk about pointers and polymorphism when Sun Microsystems says, We doan need no stinkin’ pointers!? (There’s that phrase again—if you have no clue where it came from, you’re in for a treat when you watch the classic film, The Treasure of Sierra Madre.)
Here’s the Deal
Given the orientation of this blog (ActionScript 3.0 Design Patterns), we really ought to be able to nail the jelly to the tree—polymorphism being the jelly in this case. This is where you come in:
Write a nice clear explanation of polymorphism so that a first-time OOP novice can understand it on an intuitive level as it relates to ActionScript 3.0 and design patterns.
We had our shot at it in Chapter 1, and while we didn’t blow it, we stuck to the technical side. We’d like to see something that has a visceral link between design patterns, polymorphism and ActionScript 3.0. These are the rules:
- Do not make it about you. This is for a bright person who may not have a huge technical background like you do.
- No mention of Java. (Yes….I know I did, but that was entre nous and not for someone learning ActionScript design patterns and OOP for the first time.)
- Explain pointers, polymorphism and their relationship to design patterns.
- This is not an exercise in showing us how smart you are. Everyone who reads this blog is smart; so we know you’re smart. It’s about clarity so we don’t end up with one of those “This may be confusing” warning labels.
- Provide an ActionScript 3.0 example. The example should show how polymorphism and design patterns are related.
- No paraphrasing. Your explanation should be in your own words to someone you may eventually work with and needs a nice clear explanation.
Now I don’t mind those comments that begin, “Bill, you’re as dumb as a box of rocks…”, but for this particular post, I hope to see something from you that you believe will help others. If you send in some rambling comment indicating that you’re a really serious programmer and know more than God, we’ll probably defer putting it on the blog. This is for others and clearly so. So I don’t care whether you learned design patterns day before yesterday or you’re an old hand. All I want is a nice clear explanation of why those learning design patterns and OOP should care about polymorphism and how it helps to become a better programmer.

The ActionScript 3.0, Design Patterns and Polymorphism: What’s the Point? by William B. Sanders, unless otherwise expressly stated, is licensed under a Creative Commons Attribution-Share Alike 3.0 United States License.

Bill Sanders
I think a lot of the problem comes from people confusing ad-hoc polymorphism (overloading and inheritance) and parametric polymorphism (generics), and not realizing this when they are searching for info on polymorphism . The article you mentioned deals mainly with parametric polymorphism, and explains it with math (and math that is normally taught at the graduate level). Most OO people are interested in ad-hoc polymorphism.
I would also suggest that bringing in an implementation concept link pointers and references into an initial discussion about the concepts of polymorphism is inappropriate.
Polymorphism is the glue that holds Strong Typing, OOP, and Design Patterns together.
The main benefit is encapsulation of the specific type of an object. If you don’t need to know something is of type Bear and just of type Mammal, you want to be sure you’re only invoking Mammal methods, and that all Mammals will have the capabilities you are relying on.
In dynamic languages , whenever you manipulate two different objects that share a set of methods or properties with the same block of code, you’re doing polymorphism in your head.
Formal polymorphism is how you bring this technique into a strongly-typed environment. This gives you the best of both worlds; the flexibility to swap implementations and reuse code, and the type safety of a more strict language.
For a real life example, consider what would happen if you couldn’t treat Sprite, MovieClip and Bitmap all as DisplayObject. This is polymorphism at work.
I ll do it the most simple way i can.
If i need a instance to move i will only need to know that this instance can do so, i don’t really care if it is a car, a man , a bear or whatever, that is why i will say my instance is a IMobile type that can be asked to move() , the result can be to roll, walk, run, dive, jump, fall….depending on what really the instance is.
So the relationship with design is that my IMobile instance can easily be replaced by another one that will do the same thing…or another but at least it will do it another way without rewriting the whole application .
For the concern about pointers, actually i really don’t know since i don’t make a difference between pointers and references (i develop in AS3 not in C++)
hope it was easy for anybody to understand (and hope i got it right)…and sorry i’m french
Hello Matthew,
Ok, so you’ve separated ad-hoc polymorphism (overloading and inheritance) from parametric polymorphism (generics), but a beginner to OOP won’t know either one. Also, what does it all have to do with design patterns? Why should it matter to an OOP beginner who just wants to find out about design patterns that polymorphism is important at all?
Thanks for your contribution to the discussion,
Bill
Hi Andrew,
Very nice. However, you’re still too advanced. A newbie to OOP may not know what a strongly typed language is or that it is important to glue strongly typed elements together with Design Patterns and OOP. What real advantage is there to doing so?
You have the perfect tone to your explanations–neither condescending nor aloof. That is pitch perfect, but take a look at the bullet points in the original post and see if you can bring them together.
Thank you very much for your thoughts,
Bill
Bonjour Udon,
Your English is far better than my French. So no need to apologize. We are grateful that you shared your thoughts with us. I understand your point, but you need to show why polymorphism is important to design patterns. Your example c’est bon. Pourquoi est polymorphism important design patterns?
Amicalement,
Bill
Bill, consider my initial comment a remark about the problem with beginners learning about polymorphism, and not a explanation.
How about this? Not quite the explanation you are looking for, but another general thought that may help others.
Most examples on ad-hoc polymorphism focus on the is-a type of relationship (a Cat is a Pet), and this frames the thought process in the beginners mind to think of objects as “nouns” for lack of a better word. I also think that most examples focus on the sub-class and not the base-class.
On the other hand, I think that design patterns epitomize the does-this type of relationship (a Subject notifies Observers). A design pattern emphasizes the actions, or set of “verbs” associated with the objects. I also think that the GOF and AS3DP books focus more on the base-class (ie, the patterns) rather than the sub-classes.
The difference between is-a and does-this, may be subtle (or only exist in the readers mind), but I think it is key to explaining the concepts to a beginner.
I think another complication with beginners is that many polymorphism examples will be about a single class hierarchy. In many (most?) cases, design patterns involve several intertwined, but unrelated classes (in the hierarchical sense).
Hi again Matthew,
Whoaa, that is very interesting. I really like the idea
I think you’re right, not only technically but where the emphasis should be. I would not disagree with your noun vs. verb emphasis, but I would say that design patterns emphasize the relationships between classes (which include the verb element) rather than the verb element itself.
Thank you again for your insights,
Bill
“Your example est bon. Pourquoi le polymorphisme est’il important pour les design patterns?”
Well, i think the important is to talk to someone who can do actions instead of focusing on the the nature of the guy we are talking to..
by the way i did not understand what you mean by “parametric polymorphism (generics)”
Whenever the talk comes to design patterns the main goal of them is to target the very likely CHANGE in software development. This fact should not be hard to understand even for beginners.
Then we have the term ‘loose coupling’. And that this is something we want is also easy to understand when you have CHANGE in mind – when you want to change something that is really strongly connected you have to work hard. We want to avoid hard work.
So, polymorphism makes it possible to write code that is NOT strongly connected. And it is doing this by treating objects in a more general way than their individual classes.
Hi Mark,
I agree that change is key to any understanding of design patterns and tying polymorphism to change is certainly a good idea. Indeed loose coupling as a concept and a process is important as well and should be included.
However, exactly how polymorphism works to help achieve change by loose coupling is what still a bit up in the air. The idea that we want to avoid hard work is equally important!! Most have the idea that design patterns require more work, but in the long run, you are absolutely right.
Thanks for your thoughts,
Bill
Udon,
I did not mean to appear that I was focusing on you instead of your comments. Because my French is very poor, I may have left the wrong impression, and I apologize if I did. Your comments are quite valuable to us.
Parametric polymorphism (genetics) was introduced to the discussion by Matthew. Generic types are type variables that can be instantiated with an appropriately specific type for each instance of a class. Languages with parametric polymorphism allow generic types instead of using the lowest common denominator class (usually Object). However, as Matthew points out, our focus is on ad hoc polymorphism with its focus on overloading and inheritance.
Kindest regards,
Bill
Polymorphism… One of our neighbour planets is discovered to be life sustaining, containing masses of frozen waters, and an atmosphere of non-poisonous gases. So, earthly colonisation efforts kick off.
First, an earthly committee of worldly powers are established for this endeavour. It is decided that all citizens of this celestial body will have to be sworn in, and committed to a new set of rules under oath.
A horde of candidates apply for this prestigious opportunity: citizens from Russia, Belgium, Malawi, Brazil, South Africa, UK, Canada, Ivory Coast, New Guinea – from a very varied cultural background.
So, as you might expect, the example is steering towards the new communal behaviour, which is the set of rules, principles, values, and laws that act as the glue of the ad hoc society. Yet, everyone in this new community is also allowed to retain their sense of cultural identity within their private domain (their local behaviour).
In the polymorphic sense, we now have behaviours for all citizens, including vote(), singTheAnthem(), while some could sing singOCanada(), singGodSaveTheQueen(), singNkosiSikelele(). vote() is guaranteed to work on all of them, but singNkosiSikelele() not.
Sadly, a virus breaks out on the planet, causing the afflicted to die in a rather messy, yet spectacular implosion. The infected are quickly quarantined, and the remaining are medically tested to be cleared. Now the virus-free citizens have an additional commonality, which is lacking from the quarantined citizens. The free citizens have behaviour loosely described as walkFree(), while the quarantined citizens do not have that luxury. The latter citizen could still, albeit faintly and hoarsely, singTheAnthem().
It is exactly then, when they tend to rely on their pointers to *homeCountry, which for some, point to the same thing, but not necessarily. Because they are all first generation immigrants to this new planet, they all have this pointer. Whether this is a pointer or a waning reference, it conceptually remains the address to the little spot in their brains that remember what they gave up before their sense of adventure took over, and are now paying for dearly.
That might be polymorphism to my non-programming friends. I’ll be testing it tonight on my wife when I get home.
Pieter,
I think that your approach has a great deal of merit. Years ago, a friend with a doctorate in Astrophysics from Berkeley was given the job of teaching introductory physics. So he and a friend put together a manuscript that was a science fiction story to explain physics . Naturally, no publisher would touch the manuscript, but privately printed copies made their way through different institutions to the delight of both the professors and students who were given this unique way of learning. In the same way that the Head First series has broken the mold and Google has employed comic book-like pages to explain Chrome, I think that you may have a way that would be both useful and effective for explaining OOP concepts.
How about putting together a series of science fiction stories in comic book form to explain ActionScript 3.0 design patterns?
Thank you for the creative approach,
Bill
I realized the value of polymorphism while working on a very simple and common AS3 project: a media player that handled 3 media types ( flv, swf and image ).
I created three classes to take care of loading and handling each media type: FLVPlayer, SWFPlayer and ImagePlayer. Each class contained the same simple methods( load, play, pause, stop ).
Each class implemented a common interface called IMedia
The IMedia class looked something like this:
By implementing the IMedia interface each of the three classes entered into what could be thought of as a “contract”. This contract of sorts let other objects know that these four methods were available for public use.
The alternative to implementing the IMedia interface could have been just extending an AbstractMedia class that defined a skeletal set of methods with no actual functionality. It might look something like this:
The disadvantage to this would be that each of the sub-classes by way of inheritance would be Sprites. Not a huge problem but somewhat strange and possibly limiting if in the future we were to add an MP3Player class. There would be no reason to make an MP3Player a display object. By that I mean the actual code that loaded and played an mp3 not the visual elements like buttons and/or progress bars.
Back to IMedia…..
To control the three different media classes I created a MediaController class. The job of this class was to determine what kind of media was being played and then choose the appropriate player. Each media object was represented in a database and had a “type” property that could be used to make this distinction. The MediaController class looked something like this.
The value here is that the media controller didn’t need to know any of the specifics of how the three media classes actually handled their loading or playing. Each of the players could be treated essentially the same by outside objects. With a slight addition to the MediaController class new media player types could easily be accommodated.
This went a little longer than intended and I didn’t even write about how cool it can be implement multiple interfaces!!
Hi IBloggable,
Interesting post and example. A couple of things. Why would an abstract class (in the AS3 way) require an extension of Sprite? Do each of the three players extend a Sprite? And if they do, wouldn’t it be easier for the abstract class to do so and then extend the players from the abstract class?
One other thing…where’s the polymorphism? I believe you implied it here,
I like the whole idea and where you took the example. Could a beginner get there, though?
Thanks for your comment,
Bill
Hi Bill,
In general an abstract class wouldn’t have to extend sprite, but in the case of the mentioned media players ( flv, image, and swf ) it would in order to get them on the stage. That is fine for most cases but it could be burdensome if say you wanted one of the media players to extend some other class besides sprite.
The polymorphism is there in that each media player has the same API with completely different internal implementation. Sure there is some logic to decide which type of player to use, but the code to do so is minimal in comparison to what you might have if each media player were unique in it’s API.
As for whether or not a beginner could get there… that is a good question. It’s a seemingly simple concept but apparently quite difficult to articulate.
Thanks :)
Hi IBloggable,
You pretty much hit the nail on the head with,
Further, as you note, one of the trickier aspects of working with design patterns and Flash/Flex is the whole issue of getting things on the stage. Somewhere between the Client and all the other classes that make up the design pattern–and between abstract and concrete classes–is having what you create show up. While providing an example with output generated with the trace statement is often clearer in showing the structure than one using objects on the stage, there’s always that issue of organizing the elements of a program so that they are accessible to the user.
Beginning on page 233 in our book, Chandima provides a very nice explanation of the Display List along with the roles of the DisplayObject and DisplayObjectContainer in getting everything where it belongs in an application. That is an entirely different blog post I hope to get to in the not-too-distant future.
Thanks again for your wisdom,
Bill
@Bill: I think, I’ve spotted a misunderstanding within your conversation with udon. I’m sure his words
were just targeting on the case of polymorphism, not on you supposed to insult him in any way.
Best regards!
(Disclaimer: My German is much better than my English, that in turn is much better than my French).
Hi DK,
Ach du lieber himmel! I see now–it was polymorphism. I hope I never unintentionally insult anyone on this blog with my poor language skills. Thanks for the clarification.
Kindest regards,
Bill
Here’s how it was explained to me once in an analyst class, and how I explained it to my students in C++.
Let me start by backing up…It’s a laudable goal, but I really don’t think (and not because I’m a pessimist) that you can start an non-OOP beginner with concepts like polymorphism right out of the gate, and expect them to understand the benefits of OOP by the end of the introduction.
OOP, in my experience, is something you kind of have to walk all the way around, and then wade through a few times before the real benefits of the OOP (and design patterns) way of life makes complete and clear sense.
These “this won’t make sense” disclaimers are right, but for the wrong reason. The concepts in and of themselves don’t make sense because it also takes experience, putting the concepts to work for you. Could you understand baseball from a rule book, without ever once seeing a game? Or without understanding the basic notions of gravity, teams, players, sports, and scores? It’s easy for (experienced) programmers to forget how many times we had to fall down before “int x = 10;” was as natural as breathing, and you can go from the shallow end of the pool to the deep end quite quickly in code.
I think you know that, but I just had to write that down. In teaching I never once had a student that understood the whole thing entirely on the first try.
Now back to how I might explain polymorphism:
You have a CD, and you wish to listen to music. You also are a news junkie, and so you want to listen to the radio.
So you go to Best Buy (if you can still find one) and you buy a Walkman-type CD player with AM/FM radio.
You decide you want to record some of this stuff to listen to in your car, so you buy a cassette tape player (I know, my age is showing) that you connect to the CD/AM/FM player.
You now have a tightly coupled (CD/AM/FM) system and a loosely coupled (CD/AM/FM tape) system. If the AM/FM breaks you have to take the whole thing back to the store and you lose the CD player. If the tape breaks you can just replace the tape player.
The two systems have two outputs: the tape player has one and the CD/AM/FM has one. To switch from one to the other, you have to switch the headphones (or speakers) from one jack to the other. This becomes unsatisfying. So you go back to BestBuy, and you purchase a rack stereo system. Everything plugs into the amplifier, you have one set of speakers, you can add Satellite Radio, TV sound, DVD, whatever!
This is now a very loosely coupled system, all sharing a single output.
Turn the various component parts into code examples, and I think that explains polymorphism rather nicely!
As for the other part of your post, I always thought that Sun calling pointers “references” was a bit of anti-establishment rhetoric, and not much more. Java isn’t THAT much easier than C++, and certainly nowhere near as fast (as it turns out), and I think that sort of language is just a hangover from the (not so long ago) days when Sun was trying to position Java as the “Anti-C++” or “C++ for the Web.”
You know, if anyone’s still reading this thread.
Dave.
Although on second thought…I suppose my example maybe does not quite explain polymorphism (since that’s a lot of work to get to a single output) but it doesn’t maybe give a reader a sense of why one should care. Gives a target worth shooting for. Per my opening sentences, I think giving a sense of why it’s worth sticking with might be as good as it gets for teaching beginners OOP — and pretty good at that!
Dave.
Hi Dave,
You covered a lot of territory there, but I think I have a sense of what you’re trying to say. To some extent a person learning OOP and Design Patterns is told,
Often what happens is that someone approaches OOP/DP with the expectation that it will make their programs run faster or better. A response of “sort of, but not exactly…” Most DPs do nothing for faster programs and “better” can be iffy… However, if the whole enterprise is approached as one principle at at time with a clear explanation of what that principle is; then things like polymorphism seem a lot clearer.
Years ago at UCLA Neuropsychiatric Institute, they were doing some experiments with sound and frequencies. (I may get this wrong due to my lack of understanding of how sound works, but bear with me.) They took a recording of some people having a conversation, and they wanted to see at what point the sound would be unintelligible as frequencies were removed. The two researchers kept removing frequencies, but no matter how many they took out, they could understand the recorded conversation. Eventually, with almost all of the frequencies removed, they could no longer understand the sound. So they started over with a different conversation and began again. After removing a few frequencies and understanding the conversation perfectly, someone walked into the lab and asked, “What’s that racket you’re listening to?”
Apparently, by knowing what to expect, they kept automatically “filling in” the missing frequencies. I think the same is true with OOP and Design patterns. If you do not have the missing parts, such as the basic principles behind OOP and Design Patterns, the explanations really don’t make much sense. Sometimes, when I read or listen to someone talking about OOP or Design Patterns, it’s clear that they don’t know what they’re talking about—or have very little idea. I learned OOP principles in Java, but the people explaining them were either “filling in” the missing parts in the assumptions they had about the reader; or they really did not understand the concepts themselves. By jumping in and working with programming that use the concepts and at the same time re-reading the concepts I believe that someone can pick them up. In my own case, after I began adopting them and understanding them, my programs looked better and better.
However, I view this as an ongoing process that is subject to change. One good example is the Singleton. After first understanding it and coming to appreciate it, I have come to avoid it. At the first OOPSLA meeting I attended, one of the participants in our session warned us off of it, and in later reading, I came to understand the problems with the Singleton. The light came on not when I eschewed the use of the Singleton, but rather when I came to understand what problems it caused.
Thank you very much for your contribution, and I sometimes wonder whether concepts like polymorphism will ever stabilize fully in one’s mind—or even whether they should.
Kindest regards,
Bill
Yes, yes, I think you’ve grasped what I’ve said entirely. I don’t think there is an “objective OOP” out there anywhere. I think we all come to it with our prejudices fully intact.
Pointer math makes me cry, for instance, so I code around it. I haven’t found this to be too much of a limitation, though, because there are so many ways to skin a cat. No that I’ve worked with or seen my code has ever mentioned that I’m “weak” at pointers, but has maybe just reimplemented my code using pointers to make it faster. Hey, as long as you don’t change what goes into or comes out of the function, what the heck do I care? Remove the frequencies and I can still hear the conversation.
So I think this is what “this is confusing” means. It means you might get any given OOP/DP principle in a day, a month, a year, or never. And if you do get it as it applies to singletons, you might still never get it as it applies to, say, MVC. Beyond a certain point OOP becomes a state of mind, a way of thinking. I’m not trying to be zen about it, I think OOP is a tool and not a result or a process. There’s really not some straight line path anyone can take to reach enlightenment. If you have a strong math background, you might go one way. English lit might take you in another. An arts background might mean you never get there at all.
But my point is: that’s ok! To go back to the baseball analogy, there are many Cy Young winning pitchers that have batting averages of .088. That doesn’t mean they’re bad ball players, just bad hitters. Excellent pitchers, but lousy hitters. There’s a demand for them on any team. If they play in the American League their batting averages don’t matter at all. Might be about the same with OOP. The “whole package” is somewhat unattainable.