Comparison
PolymorphismvsReplace conditional with polymorphism
Polymorphism
the same call site does three different things depending on what was passed in, and there is no branch anywhere.
One name standing for behaviour that varies by the runtime type of the thing it is called on. It is the mechanism underneath most of the behavioural patterns — strategy, state, visitor and template method are all polymorphism with a particular story attached. The reason interviewers keep asking about it is that the alternative, a conditional over a type tag, is what most real code does instead, and the difference shows up on the day a fourth case is added.
Full entry →Replace conditional with polymorphism
the same switch on type appeared in four methods, and adding a case meant finding all four.
The refactoring that moves each branch of a type-based conditional into a method on the corresponding subclass, so dispatch does the branching. It pays off when the same conditional is repeated across several operations; it does not pay off for a single switch in a single place, where a class hierarchy is more machinery than the branch it replaced. Recognising which case you have is the actual skill.
Full entry →