4 ms·
I see polymorphism vs if/... more as a tradeoff. For example: Suppose the program has to make a choice. When the choice exists only in 1 place, use an if/swi
by hyperman1 5y ago
I see polymorphism vs if/... more as a tradeoff. For example:
Suppose the program has to make a choice. When the choice exists only in 1 place, use an if/switch. When the choice exists in multiple places, polymorphism centralizes it and quickly becomes the simple option.
For example, a change in law required us to make a choice based on a date:
If (thing.someBusinessDate < 2010-06-01) { doTheOldWay();} else{doTheNewWay();}
after a while, a few edge cases sprang up, and we got variants of this code hiding in multiple corners. Then the law changed again with a new cutoff date. So we adapted to polymorphism:
interface TheWay{ edgecase1(); edgecase2();...}
class TheOldWay implements TheWay{...}
class TheNewWay implements TheWay{...}
class TheNewNewWay implements TheWay{...}
TheWay wayDetector(thing){/* all the ifs here */}
Unfortunately, adding just one more 'if' was always the cheapest choice. The refactoring was nevertheless clearly a better choice: it enabled us to point out more forgotten edge cases, avoiding costly mistakes.
- viceroyalbean 5y agoI agree with you, especially in instances where that decision logic is unrelated to the data that is actually being used. In your example you'd have to pass "thing" everywhere just for that if-statement, but it might not be used for anything else. That said, I think "simple" if/else or switches are much more common than the complex cases that fit polymorphism, so it seems a bit off to have it as a general rule to prefer polymorphism.