Photo by Tim Mossholder

SOLID: Open Closed Principle

Paul Allies

--

All programs are composed of functions and data structures. The SOLID principles introduced by Robert C. Martin, help us group our code into modules and advise how to interconnect them. The whole point of application architecture is to manage change. Software requirements change all the time and we as developers need to make sure that these changes don’t break existing code.

There are 5 principles that make up the acronym are:

In this post, I will attempt to explain the OCP (Open Closed Principle).

What is the OCP?

Software entities (classes, modules, functions, etc.) should be open for extension but closed for modification.

This explanation is quite confusing if you see this for the first time. This statement, at first, seems like a contradiction.

To explain, let’s create a function which Does Not Follow OCP:

OUTPUT:
[ 'EMAIL sent', 'EMAIL sent', 'SMS sent' ]

This program takes a list of messages of different types and uses the sendMessages function to loop through them and send them one by one. When all messages are sent, a message log prints

The sendMessages function does not follow OCP because it is not open to extension. It has to know too much about the message object and can only ever handle Email and SMS messages.

What if we change the message property from “body” to “content”?

What if we want to add support for another message type?

This will surely break sendMessages. We’d be forced to modify the function.

When we write code, it’s all about anticipating the future by leaving existing code untouched and adding new functionality with new code. This prevents situations in which a change to one module will also require other modules to change.

Let’s fix the program. We can achieve OCP by changing the Message class to an interface with one send method. We can then add message classes that implement the Message interface. This polymorphism helps us implement the Open/Closed Principle.

OUTPUT:
[ 'EMAIL sent', 'EMAIL sent', 'SMS sent' ]

The sendMessages now adheres to OCP. It just does not need to know anything about the inner workings of the message object. It merely loops through the messages and invokes the public send method. The function is now unaffected by new message types or property changes.

In Conclusion

We must try to anticipate the future as best we can by writing them in a way that shouldn’t change when requirements might.

The open-closed principle allows for easier extension while reducing time spent adapting existing code

This article was originally published on Nanosoft

--

--