According to Open Closed Principle, Software entities (Classes, modules, functions) should be OPEN for EXTENSION, CLOSED for MODIFICATION.
Lets try to reflect on the above
statement- software entities once written shouldn’t be modified to add
new functionality, instead one has to extend the same to add new
functionality. In otherwords you don’t touch the existing modules
thereby not disturbing the existing functionality, instead you extend
the modules to implement the new requirement. So your code is less rigid
and fragile and also extensible. (See Reference)
Lets look at the code below which draws triangle and rectangle:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 | public class OCPViolation { class Drawer{ public void drawRectangle(Rectangle shape){ System.out.println("Rectangle is drawn"); } public void drawTriangle(Triangle shape){ System.out.println("Triangle is drawn"); } } class Rectangle{} class Triangle{} public static void main(String[] args) { OCPViolation test = new OCPViolation(); Drawer drawer = test.new Drawer(); Rectangle rect = test.new Rectangle(); Triangle tri = test.new Triangle(); drawer.drawRectangle(rect); drawer.drawTriangle(tri); } } |
Code above violates OCP principle, because if a new shape is required to be drawn, it needs change in Drawer so refactor code as below to be OCP compatible:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 | public class OCPCompatible { class Drawer { public void draw(Shape shape) { shape.draw(); } } interface Shape { public void draw(); } class Rectangle implements Shape { public void draw() { System.out.println("Rectangle is drawn"); } } class Triangle implements Shape { public void draw() { System.out.println("Triangle is drawn"); } } public static void main(String[] args) { OCPCompatible test = new OCPCompatible(); Drawer drawer = test.new Drawer(); Rectangle rect = test.new Rectangle(); Triangle tri = test.new Triangle(); drawer.draw(rect); drawer.draw(tri); } } |
No comments:
Post a Comment