2

Lets say I have a method like this :

public void sketch(Shape shape){
 switch(shape.getType){
   case CIRCLE: 
      Circle circle = (Circle)shape;
      circle.drawCircle();
      break;
   case RECTANGLE: 
      Rectangle rectangle= (Rectangle)shape;
      rectangle.drawRectanle();
      break;  

  }
}

The above code can be easily refactored by having an Shape interface that knows how to draw itself. Then concrete classes like Circle and Rectangle will implement draw(). The above client code then becomes as given below (way more readable and uncluttered than the previous snippet):

public void sketch(Shape shape){
   shape.draw();   
}

So my question is regarding the usages of switch in a OO language that supports polymorphism. Is it always considered an anti-pattern? Is there any situation when switches can become a life saver?

Geek
  • 26,489
  • 43
  • 149
  • 227

0 Answers0