Create subclasses matching the branches of the conditional.
It is used to replace a series of conditional statements with polymorphic behavior, in order to improve the readability and maintainability of the codebase. The result is that the proper implementation will be attained via polymorphism depending on the object class. This can be useful when a class or method has a large number of conditional statements that make it difficult to understand or maintain. In summary, replace a series of conditional statements with polymorphic behavior.
For example, consider the following class, which has a series of conditional statements that determine how to handle different types of shapes:
handleCircle(shape);
}
handleRectangle(shape);
}
handleTriangle(shape);
}
}
}
To make the class more readable and maintainable, we can replace the conditional statements with polymorphic behavior by creating separate classes for each shape type and having them inherit from a base Shape class:
}
}
}
}
}
}
}
}
shape.
}
}
shapeHandler.
shapeHandler.
shapeHandler.
In this example, we have replaced the conditional statements with polymorphic behavior by creating separate classes for each shape type and having them inherit from a base Shape class. Each class has its own implementation of the handle method, and the handleShape method of the ShapeHandler class simply calls the handle method on the passed in shape object. This improves the readability of the ShapeHandler class by reducing the number of conditional statements it contains and making it clear that it performs a specific action for each shape.