The Open Closed Principle

The open closed principle of object oriented design states:

Software entities like classes, modules and functions should be open for extension but closed for modifications.

The Open Close Principle encourages software developers to design and write code in a fashion that adding new functionality would involve minimal changes to existing code. Most changes will be handled as new methods and new classes. Designs following this principle would result in resilient code which does not break on addition of new functionality.

In this article, we will explore the open closed principle via an example of a resource allocator.

Original Code (Violates the Open Closed Principle)

The code below shows a resource allocator. The resource allocator currently handles timeslot and spaceslot resource allocation. It is clear from the code below that it does not follow the Open Closed Principle. The code of the resource allocator will have to be modified for every new resource type that needs to be supported. This has several disadvantages:

Thus we can say that extending the design involves considerable code change.

Resource Allocator (Violates Open Closed Principle)

Code Modified to Support Open Closed Principle

The problems with the above design is that it violates the Open Closed Principle. The following code presents a new design where the resource allocator is completely transparent to the actual resource types being supported. This is accomplished by adding a new abstraction, resource pool. The resource allocator directly interacts with the abstract class resource pool.

This has several advantages:

Resource Allocator (Follows Open Closed Principle)

Open and Closed

The above design follows the open and closed principle. The Resource Pool is open for extension as new resource pools can be added without much impact on the rest of the system. The Resource Allocator is closed for change, as no changes need to be made to it for enhancing the system.

As you can see the above has been achieved by using two techniques:

If this principle is followed during the design, most changes to the system would be in terms of adding new classes/methods. Changes to existing classes/methods would be minimized.

Another Example

Consider another example of a Call_Manager object. The Call_Manager manages a Call abstract class. The Call_Manager design is open for extension but closed for modification. Addition of a new call type requires writing a new class that inherits from Call. No changes are needed in the Call_Manager.

call inheritance: open close principle example

C# code for the example is presented below:
 

Open Closed Principle Example

Related Links