Objects or entities should be open for extension but closed for modification
To make it easy to understand, to add functionality to a class, you shouldn't modify the code that exists in it. An easy way to identify this is if the code needs ifs for every new feature.
One way to adhere to the open-closed principle in JavaScript is to use composition and the strategy pattern. For example, let's say we have a ScientificCalculator class that has a method to perform a specific calculation. To add a new type of calculation, like multiplication, we can create a new Multiplication class that implements a calculation interface and use it as a strategy in the Calculator class. This way, we are not modifying the original ScientificCalculator class, but instead extending its behavior through composition.
The code example for this case:
}
}
}
}
// Output: 7
calculator.
// Output: 3
In this example, for each new necessary operation that the calculator needs to perform, it is not necessary to modify the existing code inside it.
Another way would be to use inheritance and polymorphism, but in this approach it is necessary to be careful not to violate the Liskov Substitution Principle.