Software

SOLID (O) – Open/Closed Principle

Classes should be open for extensions but closed for change.

You should consider a class as being “closed” to editing once it has been:

  • Testing to be functioning properly.
  • All the attributes and behavior are encapsulated.
  • Proved to be stable within your system.

Once you’ve reached a point in development where you’ve already finalized most of your design decisions, and have implemented the most of your system, then you should consider “closing” your classes. It’s needed to avoid introducing undesirable side effects (of course it’s still acceptable to modify the code if need to fix bugs).

Then, what do you do if have to add more features? This is where the “open” part of the design principle comes in. There are 2 different ways to extend your system using the open principle.

The first one is through inheritance of a superclass. The idea is that when you want to add more attributes and behaviors to a class that is considered closed, you can simply use the inheritance to extend it. This way, your subclasses will have all the original functions of the superclass, but now you can add extra features in the subclasses. This helps to preserve integrity of the superclass.

OpenClosed Principle Class Diagram.png

The subclasses can also be extended. so you can use Open/Closed principle to continually extend your system as much as you want:

Extended OpenClosed Principle Class Diagram.png

You may reach the point where you no longer want a class to be extendable, in which case you can declare your class as final/sealed, which will prevent further inheritance.

The second way is if the class is abstract and enforces the Open/Closed principle through polymorphism. An abstract class can declare abstract methods with just the method signatures. Each concrete subclass must provide their own implementation of these method. The methods in the abstract base class are preserved and you can extend your system by providing different implementations for each method.

Abstract OpenClosed Principle Class Diagram.png

This approach is useful for behaviors that can be accomplished in different ways, like sorting or searching. (Also can use Interface, but cannot achieve the common set of attributes).

The Open\Closed principle is used to keep the stable parts of your system separate from the varying parts. While you want to be able to add more features to your system, you don’t want to do it at the expense of disrupting something that works. By using extension overcharge, you can work on varying parts without introducing unwanted side effects into the stable parts. Varying parts of the system should be kept isolated from each other.

Leave a comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.