Second SOLID principle, Open for extension and close for changes!

Wow how it is possible something can be open and close! I’m surprised! But it is possible you should design


public void Draw(Shape shape)
{
var point = CalculateStartPoint(shape);
if(shape is Rectangle)
{
DrawRectangle(point, shape);
}
else if (shape is Circle)
{
DrawCircle(point, shape);
}
}

Now think about you have new Shapre called Triangle so to make the Draw function working you need to change Draw function! So to extend your application you need to CHANGE EXISTING code which is violating OCP. So how it should be then?


public void Draw(Shape shape)
{
var point = CalculateStartPoint(shape);
shape.Draw(point);
}

Interesting, so I should add ‘Draw’ method to ‘Shape’ abstract and all implementation of ‘Shape’ should implement ‘Draw’. I like it now! So whenever you have ‘if’ or ‘switch’ based on ‘type’ of object there is a smell of OCP violation.

Ok but it is really hard to achieve this, many legacy code or in many situation it is really hard to make this working! That is correct so remember refactor it as much as possible to make sure there is no more room exists. This is engineering, finding balance and best approach!

Leave a Reply

Your email address will not be published. Required fields are marked *