Refactoring

 

Replace switches with polymorphism

What is the problem?

  • Adding a new type means changes to many files
  • This can be error prone and complex
  • Example

What is polymorphism

  • Literally, many forms
  • The same interface can be used to represent many classes
  • Example

How can we use it make code changes faster?

Example

Step 1

Find switch

Step 2

Write tests

Step 3

Add classes

Step 4

Create factory

Step 5

Refactor and run tests

Key points

  • Any time you see a switch statement, check if it could be replaced with polymorphism
  • Uncle Bob: switch statements are only okay inside a factory

Pros and cons

Cons Pros
Harder to add new methods to classes Easy to add new objects
Many more classes Reduces code and scope of changes

Polymorphism

By Tom Dane

Polymorphism

  • 323