What Is Polymorphism? (Part 2)
What Is Polymorphism? (Part 2)
Yesterday’s article, which you can read here, explains the concept of Polymorphism with regards to Object-Oriented (OO) inheritance. In our example, class Shape
is the parent to child classes Triangle
, Square
and Rectangle
. A variable of type Shape
can polymorphically hold a reference to an instance of Triangle
, Rectangle
or Square
.
However, there is more to Polymorphism than inheritance relationships. It also applies to interfaces. At first glance, this may appear surprising. In inheritance, the parent class imposes a very rigid structure on child classes – interface and concrete behaviour is passed from parent to child. On the other hand, interfaces are much looser: They make no demands on behaviour – i.e. what implementers do in their methods.
Or do they? If we have an IShape
interface containing a Circumference
read-only property, then we can expect well-behaved implementers to calculate and return an appropriate value for their circumference. And that’s all they should do. The emphasis here is on well-behaved.
What if an IShape
implementer, say Rectangle
, had a side-effect for Rectangle.Circumference
, like updating a database? That would be unexpected. It would make Rectangle
a poorly-behaved implementer of IShape
.
Interfaces imply as much about behaviour as inheriting from base classes. The Liskov Substitution Principle makes the same point:
“A program should function the same when we use a subtype instance for a base type reference“.
Meaning?
Meaning when we have a subtype implementer of IShape
, say Triangle
or Square
, then the program ought to function the same when using an instance of Triangle
or an instance of Square
. The program will certainly not act the same if a side-effect of calculating the Triangle
‘s circumference involves updating a database. It’s not in the spirit of what a reasonable programmer would expect from an IShape
implementation.
Or said even simpler – Don’t do unexpected, weird things. Maybe that is the message today. Be deterministic in your programming. Whatever you write today should make sense to you in 6 months and your fellow developers in 6 minutes.
Leave a Reply
Want to join the discussion?Feel free to contribute!