The evils of polymorphism

September 2, 2010

Polymorphism is an object oriented model that allows objects within a class to have theor own versions of a method (function).  It’s an elegant mechanism that has some positive benefits, and some serious detriments that few in the OOP community like to discuss. 

For example, you can imagine a base software class called “data”. This may have decendants (derived classes) like “relational-data” and ” XML-data”, where each of those decendants has a method specific to its own nature called search(). Algorithms for searching relational data are quite different from how a system searches XML data… so it’s natural to have specific methods for each.  In any category of things there are common capabilities and attributes that all of these things must have.  There is elegance that comes from ensuring that all derived classes have the required methods, and that a programmer needn;t know which derived class they are working with… they can trust that every object of these types (with a common parent) has these qualities and methods. So far it all seams very reasonable… until you have a reason to examine the code.

The problem with polymorphic code is that you can;t tell what you’re looking at.  Have a look at these two lines of code, calling the polymorphic versions of the search function. One of these objects if a relational class and the other is a semi-structured XML class.

pResult = pObj->search(pString);

pResult = pObj2->search(pString);

Which is which? Looking at this code, you can’t tell the object type of pObj and pObj2, nor can you tell if they are calling their own polymorphic versions of the seach method, or an implementation inherited from a parent class. In short… you can’t follow the logic by looking through the code.  OOP gurus would say “You’re not supposed to know… or care. That’s the beuty of it”. The only easy way to follow the thread is with a debugger. And that’s the rub – if you need a debugger to understand code, you’ve got problems.  Who brings a debugger to a code review? 

Maybe it’s just me. I love OOD but polymorphism just seems cruel.

Previous post:

Next post: