Total Pageviews

Monday, December 10, 2012

Open Close Principle


          The Open Close Principle states that the design and writing of the code should be done in a way that new functionality should be added with minimum changes in the existing code. The design should be done in a way to allow the adding of new functionality as new classes, keeping as much as possible existing code unchanged.
Intent
Software entities like classes, modules and functions should be open for extension but closed for modifications.

Open to Extension

New behavior is added in the future

Closed to Modification

Changed to source or binary code are not required
Example
Below is an example which violates the Open Close Principle. It implements a graphic editor which handles the drawing of different shapes. It's obviously that it does not follow the Open Close Principle since the GraphicEditor class has to be modified for every new shape class that has to be added. There are several disadvantages:
•        for each new shape added the unit testing of the GraphicEditor should be redone.
•        when a new type of shape is added the time for adding it will be high since the developer who add it should understand the logic of the GraphicEditor.
•        adding a new shape might affect the existing functionality in an undesired way, even if the new shape works perfectly
// Open-Close Principle - Bad example
 class GraphicEditor {
            public void drawShape(Shape s) {
                        if (s.m_type==1)
                                    drawRectangle(s);
                        else if (s.m_type==2)
                                    drawCircle(s);
            }
            public void drawCircle(Circle r) {....}
            public void drawRectangle(Rectangle r) {....}
 }

 class Shape {
            int m_type;
 }
 class Rectangle extends Shape {
            Rectangle() {
                        super.m_type=1;
            }
 }
 class Circle extends Shape {
            Circle() {
                        super.m_type=2;
            }
 }
// Open-Close Principle - Good example
 class GraphicEditor {
            public void drawShape(Shape s) {
                        s.draw();
            }
 }

 class Shape {
            abstract void draw();
 }

 class Rectangle extends Shape  {
            public void draw() {
                        // draw the rectangle
            }
 }
Conclusion
            Like every principle OCP is only a principle. Making a flexible design involves additional time and effort spent for it and it introduce new level of abstraction increasing the complexity of the code. So this principle should be applied in those area which are most likely to be changed.

No comments:

Post a Comment