The Open-Closed Principle Looks Into The Future

 

The Open-Closed Principle

In an earlier article, we delved into the Open-Closed Principle (OCP)—the second of the five SOLID Principles. The OCP promotes the design of modular, pluggable systems. The goal? Whenever feasible, introduce new code rather than modify existing software:

The Open-Closed Principle:

A software artefact should be open for extension

but closed to modification. 

 

Unlimited Potential?

In this article, we will be asking—and answering—a tantalising follow-on question:

Can we leverage the OCP to its logical extreme and build systems where we only write new code and never modify existing code?

If achieved, the implications would be revolutionary:

  • Enhanced Stability: Untouched code signifies a stable core system, reducing the risk of inadvertently introducing bugs.
  • Faster Deployment:   New modules can be developed, tested, and deployed without having to validate the entire system.
  • Improved Maintainability:   Codebases remain clean and organised, reducing the complexity of understanding and managing intertwined functionalities.
  • Increased Collaboration:   Different teams can work on separate modules simultaneously without stepping on each other’s toes, thereby optimising development timelines.

 

The Reality

Unfortunately, reality confronts us with a different story: Bypassing all modifications in the existing code remains a theoretical ideal rather than an attainable practice. The OCP, while transformative, is fundamentally idealistic: It’s attempting to foresee future needs. And while we can successfully anticipate some likely requirement changes and allow for those, others will always elude us. 

 

Consider this scenario: our business adopts PayPal for its e-Commerce operations. With an eye on the future, we recognise the rising popularity of gateways like Stripe and Braintree. In anticipation of a possible switch, we introduce an IPaymentGateway interface into our system. This move ensures that we’re prepared for imminent shifts in payment preferences.

By adopting such foresight, we aim to pinpoint likely shifts and buffer our designs against them.

 

Yet, the future remains notoriously unpredictable. After all, didn’t the anticipated robot rebellion of the 90s turn out to be more sci-fi than reality? ;D

 

 

Joking aside, sometimes changes will be unexpected. Maybe the business wants a line manager to receive a notification email for each e-commerce purchase. We had not anticipated that. Or that customers who bought from a particular product category should be sent a promotional email. 

There are myriads of unforeseeable ways in which a system could evolve. In those instances, we will need to make changes to the existing code. 

 

So, design your systems with the OCP in mind. However, know that you will still need to modify what’s already there.