Open/Closed Principle
The entities within your software (classes, functions, etc.) should be open for extension (and parameterisation), but closed for modification. Extension in this context means adding/changing behaviour.
You should structure your application so that you can add new functionality with minimal changes to existing code. Interfaces are your friend along with the Single Responsibility principle.
If the entities within your software only do one thing you will move towards achieving true Open/Closed nirvana. Each of your classes should implement a cohesive set of related functions. If you find functionality within a class that does not fit the name of the class consider moving it to another class.
If you are creating abstractions, don’t let the consumer of your abstraction depend on anything but the public contract you provide for the abstraction.
Two things to watch out for that indicate you aren’t following the Open/Closed Principle are:
- A class that uses another class and embeds knowledge about the internal workings of its dependency (making assumptions about what is returned from methods).
- A class that uses an abstraction has to downcast to a specific subclass in one section.
Think of Open/Closed as a direction rather than as an end goal of your design. As you head down this path constantly check that you are still meeting the other principles such as KISS and YAGNI.
There is a caveat in that the more a class is used the more the Open/Closed principle applies.
The more a class is reused in the code base, the more stable it becomes. As a class becomes more stable it becomes safer to depend on it leading to it being used more. The more a class is reused throughout the codebase, the more important it becomes that the class adheres to the Open/Closed Principle so that small changes don’t have large impacts across the codebase. Libraries, component based software, frameworks and APIs get lots of value from having classes adhere to the Open/Closed Principle.
References
http://www.artima.com/weblogs/viewpost.jsp?thread=331531
http://msdn.microsoft.com/en-us/magazine/cc546578.aspx
http://joelabrahamsson.com/entry/the-open-closed-principle-a-real-world-example