How can polymorphism replace a long if-else or switch chain?
Give each case its own class with the same method, then call that method on the object. Adding a new case means adding a class, not editing the old, tested chain.
Explain it simply
A chain like "if type is bus, charge 10; else if type is metro, charge 15" must be edited every time a new transport appears, and that is where bugs creep in. If each transport knows its own fare, the caller simply asks "what is your fare?".
Example
class Bus { fare(km) { return km * 2; } }
class Metro { fare(km) { return km * 3; } }
class Auto { fare(km) { return 30 + km * 12; } }
function total(trip) {
return trip.fare(10); // no type checks
}
console.log(total(new Bus())); // Output: 20
console.log(total(new Metro())); // Output: 30
console.log(total(new Auto())); // Output: 150Adding a Cab class needs no change in total. That is the Open/Closed Principle at work. A small, stable switch that never grows is fine; the smell is a chain that appears in many places.
What to say in the interview
"I replace type-checking conditionals by moving each branch into a class that implements a common method, then call it polymorphically. New behaviour is added by writing a new class, so existing code stays untouched."
Common mistakes
- Turning a two-case, never-changing condition into a class hierarchy. That adds more code than it saves.