Replace Conditional with Polymorphism is a refactoring technique where conditional statements are replaced with polymorphic classes and methods. Polymorphism, a fundamental principle of Object-Oriented Programming (OOP), allows objects of different types to be treated as objects of a common super type. This can be leveraged to create a more flexible and maintainable codebase.
When to Apply
This refactoring technique is particularly useful when:
- A method contains complex conditional logic based on the type or properties of an object.
- Adding or modifying behavior involves changing the conditional logic.
- The conditional logic tends to duplicate in various parts of the application.
- Code readability is hampered due to nested or complicated conditional statements.
Consider a simple example where a class, ‘Bird’, behaves differently based on its type.
If we want to create a bird of type
NorwegianBlueParrot and get its speed, we will have to do the following
With the refactoring, you’d replace the conditional with polymorphism, and the same logic would look like this:
After the refactoring, getting speed of a particular bird simply requires creating an object of its type and calling the function.
Pros of Replacing Conditional with Polymorphism
Simplicity: This refactoring simplifies code and reduces complexity, making the code easier to understand and maintain.
Enhanced Reusability: By moving the behaviors into their own classes, you can reuse them wherever necessary, thus promoting code reuse.
Extensibility: It’s easier to add new types of behavior in the future as each type resides in its own class. You just need to add a new class for a new behavior type, promoting the Open/Closed principle (open for extension, closed for modification).
Strong Typing: This refactoring technique leverages the power of OOP and strong typing to reduce the risk of errors. It also makes the code more robust as the behavior is now tied to the object’s type, not to an arbitrary string or integer.
Cons of Replacing Conditional with Polymorphism
Over-Engineering: In some cases, this can lead to over-engineering, especially for very simple conditions. It’s not always necessary to introduce a whole class hierarchy.
Increased Number of Classes: This technique can significantly increase the number of classes, which can make the codebase harder to navigate and understand.
Refactoring Effort: The process of refactoring a large codebase to replace conditionals with polymorphism can be time-consuming and error-prone. However, the long-term benefits of cleaner, more maintainable code often outweigh the initial effort.
“Replace Conditional with Polymorphism” is a powerful refactoring technique that can greatly simplify your code and make it more maintainable, readable, and flexible for future modifications.