Table of contents
1.
Introduction
2.
Example of Open-Closed Principle Violation
3.
Fixing the Open Closed Principle Violation
4.
Tips for applying Open Closed Principle
5.
Benefits Of Using Open Closed Principle
6.
Frequently Asked Questions
6.1.
What are some techniques for fixing a violation of the Open Closed Principle?
6.2.
Can the Open Closed Principle be applied to non-object-oriented code?
6.3.
Are there any downsides to following the Open Closed Principle?
7.
Conclusion
Last Updated: Mar 27, 2024
Medium

Open-Closed Principle in System Design

Author Suraj Pandey
2 upvotes
Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction

The Coding Ninjas dev team has a software developer tasked with building a new feature for the company's Coding Ninjas Studio platform. The developer decided to work on the assigned feature and started coding. While coding, he realized he needed to modify existing code to add new functionality.

So he went ahead and made the necessary changes to the codebase, but he soon realized that these changes would have effects on other parts of the codebase that he hadn't anticipated. As a result, he had to spend a lot of time debugging and fixing bugs in various parts of the code affected by this change.

The Open-Closed Principle (OCP) is used to avoid situations that were faced by the developer where he modified one part of the codebase that caused unintended effects on other parts of the code. In other words, the principle states that software entities should be open for extension but closed for modification.

Open Closed Principle in System Design

From that day onwards, the developer makes sure to implement the open-closed principle in all his upcoming projects, which not only eases his work but also helps his team develop high-quality software that is easy to maintain and extend.

In this blog post, we'll learn about the Open-Closed Principle of SOLID principles, its benefits, and how to apply them to our software projects. So let's get started!

Example of Open-Closed Principle Violation

The Open-Closed Principle (OCP) is violated when adding new functionality requires changes to existing code.

Here's an example of a violation of the OCP in C++:

Let's say we have a PaymentProcessor class that is responsible for processing payments. The PaymentProcessor class has a processPayment() method that takes a payment object as an argument and processes the payment. 

Here's what the implementation might look like:

class PaymentProcessor {
public:
  void processPayment(Payment* payment) {
    if (payment->type() == "CreditCard") {
      // Process credit card payment.
    } else if (payment->type() == "PayPal") {
      // Process PayPal payment.
    } else {
      // Unknown payment type.
    }
  }
};
You can also try this code with Online C++ Compiler
Run Code

This implementation violates the Open Closed Principle because adding a new payment type requires modifying the existing code. 

For example, if we want to add a new payment type, such as a Bitcoin payment, we would need to modify the processPayment() method.

Fixing the Open Closed Principle Violation

We can use simple object-oriented techniques like inheritance and polymorphism to fix the violation of the Open-Closed Principle in the previous example.

First, we can create a base Payment class that has a process() method, which is responsible for processing the payment. We can then create subclasses for each payment type, such as CreditCardPayment, PayPalPayment, and BitcoinPayment. 

Each subclass will override the process() method with its own specific payment processing behavior.

Here is an example code that shows how to fix OCP violation for previous payment processing example:

class Payment {
public:
  virtual ~Payment() {}
  virtual void process() = 0;
};

class CreditCardPayment : public Payment {
public:
  void process() override {
    // Process credit card payment.
  }
};

class PayPalPayment : public Payment {
public:
  void process() override {
    // Process PayPal payment.
  }
};

class BitcoinPayment : public Payment {
public:
  void process() override {
    // Process Bitcoin payment.
  }
};

class PaymentProcessor {
public:
  void processPayment(Payment* payment) {
    payment->process();
  }
};
You can also try this code with Online C++ Compiler
Run Code

In this example, we created a Payment base class with a pure virtual process() method, which defines the behavior for processing a payment. We then created three subclasses for each payment type, each with its own implementation of the process() method.

Finally, we updated the PaymentProcessor class to accept a Payment object instead of a payment type string. This way, when we want to process a payment, we simply create the appropriate Payment object and pass it to the processPayment() method of the PaymentProcessor. 

This way, we can add new payment types without modifying existing code, and we can ensure that the open-closed principle is followed.

Tips for applying Open Closed Principle

Here are some tips for applying the Open Closed Principle in our code:

  • Use Abstraction to Define Object Behavior: Abstraction is an important concept of the Open-Closed Principle that allows us to define the behavior of our objects without being tied to a specific implementation and can be achieved through abstract classes or interfaces.
     
  • Avoid Tight Coupling:  Tight coupling is a coding practice where code depends on the specific implementation of other objects. This makes the code difficult to modify or extend. To avoid tight coupling, we can write code that interacts with an abstraction rather than a specific implementation.
     
  • Using Inheritance and Polymorphism: Inheritance allows us to create a hierarchy of classes where a subclass inherits properties and behavior from its parent class whereas polymorphism allows us to write code that can work with different types of objects as long as they have a common interface. By using inheritance and polymorphism, we can create a common interface that a set of objects can implement.

 

By following these tips, we can make our code more flexible, easier to maintain, and less prone to errors.

Benefits Of Using Open Closed Principle

The Open Closed Principle (OCP) has the following advantages:

  • The Open Closed Principle (OCP) promotes modularity by reducing the need for changes to existing code when new features or functionality are added which makes the code easier to maintain and scale.
  • Second, it promotes the use of encapsulation which makes code more reusable by allowing new functionality to be added by creating new classes rather than modifying existing ones.
  • Third, the open-closed principle promotes the use of interfaces and abstract classes, which make code more testable and ensure that the code is working correctly.

 

Overall, following the Open Closed principle can make code more modular, maintainable, and scalable, as well as easier to maintain and reduce the risk of introducing bugs.

Frequently Asked Questions

What are some techniques for fixing a violation of the Open Closed Principle?

Techniques for fixing a violation of the Open Closed Principle include using design patterns such as the Strategy pattern or the Decorator pattern, using inheritance and polymorphism, and using interfaces and abstract classes.

Can the Open Closed Principle be applied to non-object-oriented code?

The Open Closed Principle is most commonly applied to object-oriented code, but it can also be applied to non-object-oriented code. The principle can be interpreted as a general guideline for writing code that is modular and easy to maintain.

Are there any downsides to following the Open Closed Principle?

One potential downside of following the Open Closed Principle is that it can lead to over-engineering if taken to an extreme. It is important to balance the need for extensibility with the need for simplicity and readability.

Conclusion

In conclusion, we have discussed the Open Closed Principle, which is an important principle of object-oriented programming.

We started by explaining what the Open Closed Principle is and why it is important. We then provided an example of a violation of the Open Closed Principle, where adding a new payment type required modifying existing code, leading to potential bugs and increased maintenance.

We then discussed how the Open Closed Principle violation could be fixed, by using simple object-oriented techniques such as inheritance and polymorphism.

We also provided some tips for applying the Open Closed Principle, such as using interfaces and abstract classes.

Finally, we discussed the benefits of using the Open Closed Principle, such as increased maintainability, reusability, scalability, encapsulation, and testability.

By following the Open Closed Principle, developers can write code that is easier to maintain, test, and scale, while reducing the risk of introducing bugs and making it easier to add new features and functionality.

You can also consider our System Design Course to give your career an edge over others.

We value your feedback and insights, and we're open to any suggestions or comments you may have. Feel free to share your thoughts in the comments section below.

Live masterclass