open closed principle example javascript

Open-Closed Principle in JavaScript: The Power of Extensibility

By James Johnson
AD

The Open-Closed Principle (OCP), a fundamental concept in object-oriented programming, states that "software entities (classes, modules, functions, etc.) should be open for extension but closed for modification." In JavaScript, applying this principle enhances flexibility, maintains code integrity, and promotes reusable code. Let's delve into the implications of the OCP and learn its application through practical examples.

By following the OCP, we prevents breaking existing code while allowing for feature increments, making it an essential principle to understand and implement in your JavaScript projects. Let's explore the concept using a real-world example and demonstrate its significance.

Understanding the Open-Closed Principle in JavaScript

The Open-Closed Principle's core lies in the idea of writing software in a way that allows for easy changes without affecting existing code. In JavaScript, understanding the OCP helps in creating more maintainable and extensible code.

AD
What Is Closure In Javascript, Javascript Closure Example, How To Use Closures In Javascript, Javascript Closure Explanation, Javascript Practice Questions, Choosing Between Java And Javascript, Javascript Programming Concepts, Recursive Javascript Function, Javascript Apply Call Bind Difference
What Is Closure In Javascript, Javascript Closure Example, How To Use Closures In Javascript, Javascript Closure Explanation, Javascript Practice Questions, Choosing Between Java And Javascript, Javascript Programming Concepts, Recursive Javascript Function, Javascript Apply Call Bind Difference
a piece of paper with some type of text on it and an image of a backpack
a piece of paper with some type of text on it and an image of a backpack
Understanding Closures in JavaScript
Understanding Closures in JavaScript

To illustrate this, consider a simple logging system illustrating the stereotypical scenario where the OCP would be violated first, followed by an OCP-compliant refactor.

Violating the OCP: The Monolithic Logger

Let's start with an inefficient logging system where each log type (info, warn, error) extends the Logger base class, violating the OCP.

HTML #17: Opening, Closing & Void Elements Explained | Complete Beginner Guide
HTML #17: Opening, Closing & Void Elements Explained | Complete Beginner Guide
JavaScript while Loop: Repeat Tasks Efficiently πŸ”„
JavaScript while Loop: Repeat Tasks Efficiently πŸ”„
JavaScript Closures Explained in 5 Minutes
JavaScript Closures Explained in 5 Minutes

<script>
// Base Logger class
class Logger {
  log(message) {
    console.log(`LOG: ${message}`);
  }
}

// Derived classes for each log type
class InfoLogger extends Logger {
  log(message) {
    console.log(`INFO: ${message}`);
  }
}

class WarnLogger extends Logger {
  log(message) {
    console.log(`WARN: ${message}`);
  }
}

class ErrorLogger extends Logger {
  log(message) {
    console.log(`ERROR: ${message}`);
  }
}
</script>

AD

Applying the OCP: The Pluggable Logger

Now, let's refactor the code to adhere to the OCP by implementing a logging system that supports easy extension of new log types without altering the existing codebase.

Back to Basics - JavaScript Closures
Back to Basics - JavaScript Closures
How JavaScript Closure Can Make You Sick?
How JavaScript Closure Can Make You Sick?
Javascript Closure tutorial ( Closures Explained ) What Is Closure In Javascript, Javascript Closure Example, How To Use Closures In Javascript, Javascript Closure Explanation, Javascript Obfuscation Techniques, How To Use Javascript Cloaking, How To Use Dynamodb In Javascript, Understanding Javascript Obfuscation, Secure Authentication Methods With Javascript
Javascript Closure tutorial ( Closures Explained ) What Is Closure In Javascript, Javascript Closure Example, How To Use Closures In Javascript, Javascript Closure Explanation, Javascript Obfuscation Techniques, How To Use Javascript Cloaking, How To Use Dynamodb In Javascript, Understanding Javascript Obfuscation, Secure Authentication Methods With Javascript
a screen shot of a web page with the text closure
a screen shot of a web page with the text closure
πŸš€ Master JavaScript Loops: For, While, Do-While, For-In & For-Of Loops Explained! πŸ’»βœ¨
πŸš€ Master JavaScript Loops: For, While, Do-While, For-In & For-Of Loops Explained! πŸ’»βœ¨
Javascript window.confirm() method | Javascript tutorial
Javascript window.confirm() method | Javascript tutorial

<script>
// Define a common interface for Loggers
class Logger {
  constructor(identifier) {
    this.identifier = identifier;
  }

  log(message) {
    throw new Error('Method not implemented.');
  }
}

// Concrete loggers implement the Logger interface
class InfoLogger extends Logger {
  log(message) {
    console.log(`%c${this.identifier}: %c${message}`, 'color: blue', 'color: black');
  }
}

class WarnLogger extends Logger {
  log(message) {
    console.log(`%c${this.identifier}: %c${message}`, 'color: orange', 'color: black');
  }
}

// Introduce new loggers easily by implementing the Logger interface
class RequestLogger extends Logger {
  log(message) {
    console.log(`%c${this.identifier}: %c[${message}]`, 'color: green', 'color: black');
  }
}

const loggers = [new InfoLogger('INFO'), new WarnLogger('WARN'), new RequestLogger('REQ')];
loggers.forEach(logger => logger.log('This is a test message.'));
</script>

AD

The refactored code bases its extendability on composition rather than inheritance, making it easier to add new log types without modifying existing ones. This approach respects the Open-Closed Principle, promoting a more maintainable, versatile, and resilient JavaScript codebase.

JavaScript Conditional Operators: Write Smarter Code with ? : πŸš€
JavaScript Conditional Operators: Write Smarter Code with ? : πŸš€
an image of what are closures in the web page? and how to use them
an image of what are closures in the web page? and how to use them
Here’s What You Have To Know About JavaScript Closuers
Here’s What You Have To Know About JavaScript Closuers
SOLID: Part 2 - The Open/Closed Principle | Envato Tuts+
SOLID: Part 2 - The Open/Closed Principle | Envato Tuts+
JavaScript for Loop: The Ultimate Tool for Repeating Tasks πŸ”„
JavaScript for Loop: The Ultimate Tool for Repeating Tasks πŸ”„
a purple screen with the text closure
a purple screen with the text closure
JavaScript Loops Tutorial | for, while, do-while πŸ”₯ Easy Explanation
JavaScript Loops Tutorial | for, while, do-while πŸ”₯ Easy Explanation
an image of a black screen with the text closure
an image of a black screen with the text closure
Javascript layer animation
Javascript layer animation
Javascript Loops & Iterations
Javascript Loops & Iterations
JavaScript Under The Hood Pt. 3: Narrowing With Logical Operators
JavaScript Under The Hood Pt. 3: Narrowing With Logical Operators
Animated Close Button using HTML CSS only
Animated Close Button using HTML CSS only
JavaScript loops by Duomly
JavaScript loops by Duomly
The Open-Closed Principle at an Architectural Level
The Open-Closed Principle at an Architectural Level

Implementing the Strategy Pattern to Adhere to the OCP

marges; To further illustrate the OCP through a common design pattern, consider implementing the Strategy Pattern for an application that allows users to calculate the total price of a shopping cart based on various promotion strategies.

The Strategy Pattern delimits a family of algorithms (promotion strategies), encapsulates each one, and makes them interchangeable. Here's an example showcasing a shopping cart that uses the Strategy Pattern to adhere to the OCP.

AD

Defining the Promotion Strategies

Let's define the interface and some concrete strategies for applying promotional discounts to the shopping cart total.

<script>
// Define the Strategy interface
class PromotionStrategy {
  applyDiscount(total, ...args) {
    throw new Error('Method not implemented.');
  }
}

// Concrete strategies implementing the PromotionStrategy interface
class NoPromotionStrategy extends PromotionStrategy {
  applyDiscount(total, ...args) {
    return total;
  }
}

class BulkDiscountStrategy extends PromotionStrategy {
  applyDiscount(total, threshold, discount) {
    return total >= threshold ? total * (1 - discount) : total;
  }
}

class CashbackStrategy extends PromotionStrategy {
  applyDiscount(total, cashbackPercentage) {
    return total * (1 - cashbackPercentage);
  }
}
</script>

Configuring the Shopping Cart with Promotion Strategies

Next, let's build the ShoppingCart class that can be configured with various promotion strategies, adhering to the OCP.

<script>
// Define the ShoppingCart class that respects the OCP
class ShoppingCart {
  constructor(strategy = new NoPromotionStrategy()) {
    this.strategy = strategy;
    this.items = [];
  }

  addItem(item, quantity) {
    this.items.push({ item, quantity });
  }

  // When calculating the total, we can apply any discount strategy
  getTotal() {
    const total = this.items.reduce((sum, { item, quantity }) => sum + item.price * quantity, 0);
    return this.strategy.applyDiscount(total);
  }
}

const Cart = new ShoppingCart(new CashbackStrategy(0.05));
Cart.addItem({ price: 10.00 }, 2);
Cart.addItem({ price: 20.00 }, 1);
console.log(Cart.getTotal()); // Displays the total after applying the cashback promotion
</script>

The refactored code base, by utilizing the Strategy Pattern, adheres to the OCP, conveniently interchangeable promotional strategies, thereby preserving the open (extensible) and closed (modification-resistant) qualities of the ShoppingCart class.

In conclusion, applying the Open-Closed Principle in your JavaScript codebase leads to more maintainable, extensible, and versatile software. By embracing this fundamental principle, you're adequately preparing your code for future modifications and improvements. Now that you've witnessed the implications through practical examples, be an advocate for the OCP in your next JavaScript project and watch your code's resilience flourish.

To begin appreciating the OCP's advantages, try implementing it in your next project or refactoring an existing one. The knowledge gained from these experiences will transform the way you approach JavaScript development, ultimatelymaking you a more competent and efficient programmer.

AD