The Open-Closed design principle

Table of Contents

The Open-Closed principle

Code (classes) should be closed to change (modification), yet open to extension.

closed: Developers spend a lot of time getting code correct and bug free. So, it is not a good idea to let anyone alter the existing code. It must remain closed to modification.

open: Feel free to extend the existing classes with any new behavior you like. If your needs or requirements change (and they will), just go ahead and make your own extensions.

The goal is to allow classes to be easily extended to incorporate new behavior without modifying existing code. What do we get if we accomplish this? Designs that are resilient to change and flexible enough to take on new functionality to meet changing requirements.

There are some clever OO techniques for allowing systems to be extended, even if we can’t change the underlying code. e.g. In the Observer pattern, by adding new Observers, we can extend the Subject at any time, without adding code to the Subject. Many other patterns give us time-tested designs that protect your code from being modified by supplying a means of extension. Decorator pattern also lets you follow Open-Closed principle.

Can we make every part of design follow the Open-Closed principle? Usually, you can’t. It takes time and effort. It may even be wasteful and unnecessary and it can lead to complex, hard-to-understand code. Following the Open-Closed principle usually introduces new levels of abstraction, which adds complexity to the code. So, you want to concentrate on those areas that are most likely to change in your designs and apply the principles there.

How will you know which areas of change are most important? It is partly a matter of experience in designing OO systems and also a matter of knowing the domain you are working in. Looking at other examples will help you learn to identify areas of change in your own designs.