Open–closed principle in Javascript.

<p>Creating a large, scalable software project for an enterprise can be a complex endeavor, especially when you&rsquo;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&rsquo;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&rsquo;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&rsquo;s create some products now.</p> <pre> const product1 = new Product(&quot;Apple&quot;,&quot;red&quot;, &quot;M&quot;); const product2 = new Product(&quot;House&quot;, &quot;blue&quot;, &quot;M&quot;); const product3 = new Product(&quot;T-shirt&quot;,&quot;green&quot;, &quot;M&quot;);</pre> <p>Now let&rsquo;s create a class for product filter, let&rsquo;s create it in a way that violates OCP.</p> <pre> class ProductFilter{ filterByColor(products, color){ return products.filter(p =&gt; p.color === color); } filterBySize(products, size){ return products.filter(p =&gt; p.size === size); } }</pre> <p>Let&rsquo;s run the code and see it in action.</p> <pre> const productFilter = new ProductFilter(); console.log(productFilter.filterByColor([product1, product2, product3], &quot;red&quot;)); // [ Product { name: &#39;Apple&#39;, price: 100, color: &#39;red&#39;, size: &#39;M&#39; } ]</pre> <p>The problem with this approach is that we need to modify the existing ProductFilter class to have more criteria let&rsquo;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>