Wednesday, 27 August 2014

Open Close Principle

Open Close Principle

What does the principle say?

OCP The Open Closed Principle: -- you should be able to extend a class's behavior, without modifying it.
The Open-Closed Principle (OCP) states that software entities (classes, modules, methods, etc.) should be open for extension, but closed for modification

We should strive to write code that doesn’t have to be changed every time the requirements change.


This is especially valuable in a production environment, where changes to source code may necessitate code reviews, unit tests, and other such procedures to qualify it for use in a product: code obeying the principle doesn't change when it is extended, and therefore needs no such effort.
Reduces the development , regression testing and maintenanace time.

How do you know its violated?

You have lots of if-else loops, switch case statements,Enums are used.
If you have not used polymorphism and inheritance in your code there are great chances that you are violating the Open-Closed Principle.


Suppose I need to calculated area of various shapes rectangle , circle , square. There are various ways to do it. But if you use if..else / Switch ...Case statements , the day it is suggested to calculate the area of an ellipse you will have to give change the code and retest.
So, what is suggested is segregate the responsibility of calculating Area to a different abstract class.
Inherit this in all the classes for which you will claculate area

Where should I implement this?

You should implement OCP after giving a proper thought on this.
You should not anticipate changes in requirements ahead of time, as at least my psychic abilities haven’t surfaced yet and preparing for future changes can easily lead to overly complex designs. Instead, I would suggest that we focus on writing code that is well written enough so that it’s easy to change if the requirements change.
Post a Comment