1

What are internal and external polymorphism?

I understand what static and dynamic polymorphism means. How does static and dynamic polymorphism relate to internal and external polymorphism?

These terms come up in one of the Robert C. Martins Clean code videos when he talks about design patterns and says "Template method uses internal polymorphism. Strategy used external polymorphism.".

I have read internal polymorphism and external polymorphism but I still struggle to understand the concept.

5

Internal Polymorphism is the most common one. You have an object with polymorphic behavior and this behavior is implemented inside this object, usually through inheritance.

So, for example you have a PhotoProcessor class, and it establishes a method for applying some filter to the provided image.

If you want new kind of filter, you inherit from PhotoProcessor and provide your own implementation to the general method.

In this case entirety of the code implementing polymorphism is inside the polymorphic class, tightly coupled to it.

So if you look at the template method pattern, then you'll notice how it relies on this kind of internal polymorphism to provide different implementations to each step of the overall templated algorithm.

Major downside: changing the contract of the base class requires changing every single dependency. So even adding a single new function to the base class means implementing it in all of the classes that inherited from it.

External Polymorphism, on the other hand, occurs when you place the actual implementation of the polymorphism outside of the class that is supposed to exibit polymorphic behavior.

For example, you have a single class PhotoProcessor and its method takes an argument which tells it what filter to apply (as an enumeration for example, or a string). Then inside of the method you just check the parameter and call appropriate code. So your processor is still polymorphic, but the implementation of different filters is not in the polymorphic method.

Strategy pattern is a common example of external polymorphism: you have a polymorphic class, which applies different behaviors based on submitted arguments. However, the actual code implementing these behavors is located in strategy classes, which are injected/provided to the polymorphic class, and not in the class itself.

External/Internal is an orthogonal pair to Static/Dynamic. Static polymorphism is about multiple methods with the same name and different signatures, one of which must be selected during compile-time based on the signature. Dynamic polymorphism is about multiple classes inherited from the same contract, method of one of which must be selected during run-time, based on the order of overrides in class's inheritors.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.