Contact Me

Replace Conditional Command With Polymorphism

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:

class ShapeHandler {

handleShape(shape) {

  if (shape.type === 'circle') {

   handleCircle(shape);

  } else if (shape.type === 'rectangle') {

   handleRectangle(shape);

  } else if (shape.type === 'triangle') {

   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:

class Shape {

handle() {

  throw new Error('Not Implemented');

}

}

class Circle extends Shape {

handle() {

  console.log('Handling circle');

}

}

class Rectangle extends Shape {

handle() {

  console.log('Handling rectangle');

}

}

class Triangle extends Shape {

handle() {

  console.log('Handling triangle');

}

}

class ShapeHandler {

handleShape(shape) {

  shape.handle();

}

}

const circle = new Circle();

const rectangle = new Rectangle();

const triangle = new Triangle();

const shapeHandler = new ShapeHandler();

shapeHandler.handleShape(circle); // Handling circle

shapeHandler.handleShape(rectangle); // Handling rectangle

shapeHandler.handleShape(triangle); // Handling triangle

 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.