This blog entry probably requires some basic understanding of programming in an Object Oriented language.
A technique in Object Oriented programming is to take advantages of Base Classes or Interfaces to make code more reusable.
So you could define an Interface with a method on it, lets say IAnimate, and you could create a class, let’s say “Animator” which takes in some kind of object that can be animated. So the constructor would look something like this:
private IAnimate animatedObject;
public Animator(IAnimate animatedObject)
{
_animatedObject = animatedObject;
}
Then let’s say this class also has a method that calls the method defined in the interface.
public void PlayAnimation()
{
animatedObject.Animate()
}
As long as your defined objects implement the IAnimate interface, you can pass them into the Animator class. The Animator class doesn’t need to know anything about what objects implement it. It doesn’t have any dependency on Cat, Dog, Fish etc. In the future, more animals can be added to the program, and the Animator never needs to change. Simple to understand for a Junior Programmer.
Colin came up with a class which completely rendered this concept pointless.
private Dog _dog;
private Cat _cat;
private Fish _fish;
public Animator(IAnimate animatedObject)
{
_dog = animatedObject as dog;
_cat = animatedObject as cat;
_fish = animatedObject as fish;
}
public void PlayCatAnimation()
{
_cat.Animate()
}
public void PlayDogAnimation()
{
_dog.Animate()
}
public void PlayFishAnimation()
{
_fish.Animate()
}
So with this design, we are still passing in an interface, but there is some bizarre casting going on in the constructor, and we save the result to the appropriate variable. We also have a method for each implementation of IAnimate, so there’s a separate method for Cats, Dog, Fish, even though they do exactly the same thing. Whatever class actually uses Animator has to know what type of animal it is for, because creating an Animator for a fish, then calling PlayDogAnimation() will crash. In the future, when new animals are added, Animator will not work without extra code changes. You would need a new variable and new method for each type of animal.
Any advantage that Polymorphism brings has been completely eradicated with this design. All that has happened is that there’s extra complexity and crashes. It shows a complete misunderstanding of such a fundamental technique to Object Oriented Programming.