Replace Conditional with Polymorphism

  • Refactor the case - when by creating subclasses and use polymorphism

Drawback

Adding a new type means you just need to add a new class and implement the required methods. Adding a new type won’t require changes to any existing classes, and it’s easy to understand what the types are, because each type is encapsulated within a class.

However, this change makes it harder to add new behaviors. Adding a new behavior will mean finding every type and adding a new method. Understanding the behavior becomes more difficult, because the implementations are spread out among the types.

Object-oriented languages lean towards polymorphic implementations, but if you find yourself adding behaviors much more often than adding types, you should look into using observers or visitors instead.

Using subclasses forces you to use inheritance instead of composition for reuse and separation of concerns. See Composition Over Inheritance for more on this subject.