Prefer If Statements To Polymorphism

25 points by BasicallyEternity


dsr

The primary problem in all code bases is the complexity of understanding what the hell is going on. The obvious solution is to minimize complexity. The problem with that is Conway's Law, and the obvious solution to that is to minimize the complexity of organizations.

So it's a people problem.

brudish

If you're using polymorphism right, it's probably still an if statement but you pushed it into a factory method on a class so you aren't peppering a thousand if statements throughout your code. If you're replacing a single if with polymorphism, it's probably overkill.

I feel like this is broadly true of every single idea on this list: the ideas listed in the post are probably fine as a first level solution and can get replaced when appropriate by a higher complexity one.

nick4

Tradeoffs are central to programming, and these are all great examples of tradeoffs to make. Sometimes they make sense, and sometimes they don’t!

One if statement instead of an entire class is usually a great trade off to make. A bunch of if statements peppered in your code instead of containing them all to a class just makes it harder to see the big picture.

LesleyLai

Yeah. If/switch/pattern matching should be the default until the added complexity make sense.

I've done a lot more refactoring from if/switch/pattern matching to polymorphism, but not the reverse. One reason is that I don't write polymorphism by default, but also once it becomes polymorphism, it is much harder to see the control flow and perform the reverse refactoring.

chad

Is pattern matching polymorphism or glorified if statements?

ryan-duve

Yes to 10 of these. No to 3.