I read the book " Perfect Code ", going through the section, the author gave an example of a method that it would be better to replace with polymorphism:

switch (shape.type) { case Shape_Circle: shape.DrawCircle(); break; case Shape_Square: shape.DrawSquare(); break; ... } 

Quote from the book: " Here, the shape.DrawCircle () and shape.DrawSquare () methods should be replaced with a single shape.Draw () method that supports drawing of both circles and rectangles. "

I can not understand the meaning of creating a new method, if you still have to write a switch in another method, can you explain in more detail how this approach is better?

    1 answer 1

     public abstract class Shape { public abstract void Draw(); } public class Circle : Shape { public override void Draw() { // implement drawing of a circle } } public class Square : Shape { public override void Draw() { // implement drawing of a square } } public class SomeUnforeseenShape : Shape { public override void Draw() { // draw Mona Lisa } } public void DrawShape(Shape shape) { shape.Draw(); } 
    • Hmm ... Really ... Thank you! : D Now 6 minutes will pass and I will accept the answer. - user189127 9:39 pm