The SOLID Principles - Open-Close
Exploring the SOLID Principles: Part 2 - Open-Close
The Open-Closed Principle (OCP) states that software entities, such as classes, modules, or functions, should be open for extension but closed for modification. This means that you should be able to add new functionality to a software system without changing the existing code. In other words, the behavior of a software entity should be easily extendable without modifying its existing codebase.
Here are some examples of how the OCP can be applied in JavaScript:
Example 1: A Payment Gateway
Suppose we have a PaymentGateway class that processes payments for our application. Initially, the PaymentGateway class only supports credit card payments. However, we want to extend the PaymentGateway class to support additional payment methods, such as PayPal and Apple Pay, without modifying the existing code.
Here's an example of how we can extend the PaymentGateway class without modifying its existing code:
class PaymentGateway {
processCreditCardPayment() {
// Process credit card payment
}
}
class PayPalGateway extends PaymentGateway {
processPayPalPayment() {
// Process PayPal payment
}
}
class ApplePayGateway extends PaymentGateway {
processApplePayPayment() {
// Process Apple Pay payment
}
}
By extending the PaymentGateway class to support additional payment methods, we can ensure that the behavior of the PaymentGateway class is easily extendable without modifying its existing codebase.
Example 2: A Shape Class
Suppose we have a Shape class that represents different shapes in our application. Initially, the Shape class only supports drawing circles. However, we want to extend the Shape class to support drawing other shapes, such as rectangles and triangles, without modifying the existing code.
Here's an example of how we can extend the Shape class without modifying its existing code:
class Shape {
drawCircle() {
// Draw circle
}
}
class RectangleShape extends Shape {
drawRectangle() {
// Draw rectangle
}
}
class TriangleShape extends Shape {
drawTriangle() {
// Draw triangle
}
}
By extending the Shape class to support drawing other shapes, we can ensure that the behavior of the Shape class is easily extendable without modifying its existing codebase.
In both examples, we can see how following the OCP helps to create code that is easier to maintain, test, and reuse, since the behavior of software entities is easily extendable without modifying their existing codebase.