tags:

views:

46

answers:

1

I have recently been trying to learn about basic design principles and the OCP has me a bit confused. It makes sense that when a change happens it is preferable to extend the system rather than modify existing and working parts. But isn't this more of a principle for how to implement changes in a system rather than how to design one? Isn't all code basically open for extension by using subclassing? And how can any code be closed for modification - doesn't that just depend on how the person implementing a change chooses to use it?

Perhaps an example of some code that doesn't follow the OCP and how exactly it has violated the principle would be the most helpful for me to understand this.

Thanks

A: 

A typical example would be any logic that branches on the type of things. Doing this means that every time you need to add a new type, you have to change this code. Using virtual functions means that you can just add new classes for new types without changing existing code.

Open Closed Principle (PDF)

There are code examples in there.

Martin Broadhurst