Open–closed principle in Javascript.
<p>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.</p>
<p>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:</p>
<blockquote>
<p>Software entities (classes, modules, functions, etc.) should be open for extension but closed for modification.</p>
</blockquote>
<p>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.</p>
<p>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.</p>
<pre>
class Product {
constructor(name, color, size) {
this.name = name;
this.color = color;
this.size = size;
}
}</pre>
<p>Let’s create some products now.</p>
<pre>
const product1 = new Product("Apple","red", "M");
const product2 = new Product("House", "blue", "M");
const product3 = new Product("T-shirt","green", "M");</pre>
<p>Now let’s create a class for product filter, let’s create it in a way that violates OCP.</p>
<pre>
class ProductFilter{
filterByColor(products, color){
return products.filter(p => p.color === color);
}
filterBySize(products, size){
return products.filter(p => p.size === size);
}
}</pre>
<p>Let’s run the code and see it in action.</p>
<pre>
const productFilter = new ProductFilter();
console.log(productFilter.filterByColor([product1, product2, product3], "red"));
// [ Product { name: 'Apple', price: 100, color: 'red', size: 'M' } ]</pre>
<p>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.</p>
<p><a href="https://bilaltehseen.medium.com/open-closed-principle-in-javascript-74f0d3d87716">Click Here</a></p>