I race bikes around the Twin Cities and probably drink a bit too much coffee. I studied computer science and love building software (especially when it comes to performance and security). Here I write about athletics and hacks of all kinds.
Polymorphism in object oriented language is the practice of subclassing objects to add or modify functionality. With it, programmers can create smarter objects.
Having smarter, more efficient objects can reduce or eliminate the need for conditional statements. This is awesome because the work moves from runtime to compile time – programs execute faster. (It is just as beneficial for interpreted languages, compile time in this sense means it becomes built into the classes’ structure.)
To practice this myself (and learn some Python) I wrote this linked list. With one subclass – the EmptyNode class – of the standard node object I was able to be rid of all conditionals.
Think of the difference. In this example specifically, to add a node sans the EmptyNode class would require a check in the add method to test if this node is the last node.
In a list of 1000 items, that’s 1000 conditionals that need to execute for EVERY node addition; it would add up.
Another neat side effect is the tidy, brief, and direct nature of the code. Notice that no method is longer than 2 lines. That’s cool. (Edit: The singleton implementation for EmptyNode is 5 lines.)
Leave a Comment