Polymorphism

Polymorphism means that any object will be able to do the right thing if you send it a message it understands. If I call the Hack method of a Programmer object, a Woodcutter object, and a Butcher object, each object should be able to Hack in its own special way without knowing who sent the message.

Visual Basic supports polymorphism in two ways. First, you can achieve polymorphism by using the Object type. Any Hack method works on an Object as long as the caller uses compatible arguments and return types. This dumb form of polymorphism was available in version 4 and remains in version 5, but you should avoid it because it is terribly slow and has no type protection. On the other hand, there are times when excessive type protection gets in the way and speed isn’t critical. If you want your polymorphism dumb (that is, you don’t know the type until run time), use Object.

Most of the time it’s better to use interfaces through the new Implements statement to get fast, safe polymorphism. Visual Basic’s syntax for Implements makes it work kind of like events. I find this syntax awkward and confusing, but perhaps it’s a matter of taste. The mechanism would be more comfortable if you could typecast to interfaces to avoid creating extra object variables. But once you get used to it, Implements enables a lot of cool new techniques. Furthermore, Implements is almost a direct implementation of the powerful COM concept of interfaces. Unfortunately, some of the advantages of using COM interfaces get washed out because Visual Basic doesn’t support the types used in most standard COM interfaces.

That’s an important part of the polymorphism story, but only part. In most object-oriented languages, polymorphism goes hand-in-hand with inheritance. If Wood­cutter and Butcher both inherit from Cutter, but Programmer inherits from Thinker, then Programmer.Hack will fail in contexts that expect Cutter.Hack. There are lots of techniques you can use in languages that have both inheritance and polymorphism that you can’t do easily in Visual Basic. Java, for
example, gives you the choice of polymorphism straight or with a side of in­heri­tance, so I have to deduct for Visual Basic’s one-track polymorphism.

Rating for polymorphism: .7