Conditional branching isn’t fun for anybody, use polymorphism to avoid it.
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.)