display | more...

OCP. One of the principles of Object Oriented Design.

Bertrand Meyer first coined it in the first edition of Object Oriented Software Construction as follows:

A class should be open for extension, but closed for modification.

In other words, (in an ideal world...) you should never need to change existing code or classes: All new functionality can be added by adding new subclasses and overriding methods, or by reusing existing code.

This prevents you from introducing new bugs in existing code. If you never change it, you can't break it.

The Open Closed Principle states that in an OO software architecture, classes should be both closed in that they are complete and functional on their own, and open in that they are extendible by inheritance.

Imagine you have a class X that performs a general task, and you wish to implement code that performs a more specialised task related to the task performed by X.

You can directly alter the code of X to deal with the special case. The problem inherent in this is that you would be forever altering the code of every class in your system to deal with every special case. The classes would not be closed, and you'd have a maintenance nightmare.

You could copy the code of class X, paste it and rename the copy X'. At first this seems like a good option - after all, you've managed to keep the original X closed and allowed for an extension. You're a software engineering genius.

Actually, you're not. If you duplicate the above behaviour ten times for various special cases, you end up with a lot of strangely named classes duplicating the same behaviour again and again.

The solution is inheritance. Inheritance is a language feature that lets a class take on the properties of another, and also allows it to redefine some of these properties and add new ones. The system remains relatively simple compared to the other solutions - if you change the properties of the base class (the one inherited from), then all derived classes will take on this new behaviour. This is similar in a way to the Single Choice Principle, which states that behaviour or data should be defined at most once in a system. This way, if a change is needed, it need only be changed in this one place.

So, the solution to our above problem? Easy. Define a new class Y that inherits from X. X is closed - no changes have been made to it, no new bugs introduced - but it is also open because we were able to extend it.

Log in or register to write something here or to contact authors.