Creating a large, scalable software project for an enterprise can be a complex endeavor, especially when you’re working with multiple teams. To ensure success, you need a well-thought-out plan and a set of best practices to guide your development process.
The Open-Closed Principle (OCP) is one of the five SOLID principles of object-oriented programming and design. It’s a fundamental concept that plays a crucial role in designing scalable and maintainable software systems. The Open-Closed Principle states:
Software entities (classes, modules, functions, etc.) should be open for extension but closed for modification.
In simpler terms, the OCP encourages you to design your software in a way that allows you to add new functionality or extend existing behavior without altering the existing codebase.
Assume you are assigned to create a filter system of products for an online e-commerce platform, so you’ll start by creating some classes.
class Product {
constructor(name, color, size) {
this.name = name;
this.color = color;
this.size = size;
}
}
Let’s create some products now.
const product1 = new Product("Apple","red", "M");
const product2 = new Product("House", "blue", "M");
const product3 = new Product("T-shirt","green", "M");
Now let’s create a class for product filter, let’s create it in a way that violates OCP.
class ProductFilter{
filterByColor(products, color){
return products.filter(p => p.color === color);
}
filterBySize(products, size){
return products.filter(p => p.size === size);
}
}
Let’s run the code and see it in action.
const productFilter = new ProductFilter();
console.log(productFilter.filterByColor([product1, product2, product3], "red"));
// [ Product { name: 'Apple', price: 100, color: 'red', size: 'M' } ]
The problem with this approach is that we need to modify the existing ProductFilter class to have more criteria let’s say we were asked to create a filter by color and size then we will end up creating another method in our ProductFilter which violates OCP.