First I showed how the code violates the principle, and how to refactor it so it doesn't. To carry out the implementation, we used JavaScript classes to illustrate how you can get it done with JavaScript object-oriented programming. In this article, you learned about the open-closed principle, its benefits, and how to implement it. Now if you want to add new discounts, you only need to add to the discount object, not the existing function that calculates the discount. And that violates the open-closed principle in the process. That’s because in code like this, there’s a very real possibility you will modify the class using the switch or if statements. The first example of the open-closed principle I will show is a class using a switch or multiple if statements. How to Implement the Open-Closed Principle in JavaScript And if you want, you can unit test each class successfully. With this the code is more flexible and maintainable. Your code is more maintainable, testable, and flexible: following the OCP will make your codebase loosely coupled. You can avoid bugs: since you don’t have to edit the existing code before adding new features, you can avoid introducting unnecessary bugs. This can help you and your team members focus on what is necessary when it’s time to implement new functionalities. It means you can add new features without performing too much editing on the existing code, or none at all. You focus on what is necessary: as the OCP states, your code is closed for modification. This means if you’re following the open-closed principle, you don’t need to reinvent the wheel (and rebuild everything) when you want to add new features. You don’t need to re-invent the wheel: as the principle states, the code you and your team are working on is closed for extension. Here are some reasons why you should be using the open-closed principle: Why Should You Use the Open-Closed Principle? If you want to add new functionality to your existing code and you have to modify it before you add the new functionality, then you are not following the open-closed principle. The open-closed principle encourages software engineers to focus on what’s necessary when it’s time to add new functionalities. It means you or your team members should be able to add new functionalities to an existing software system without changing the existing code. Well, in the land of software development, it’s possible for an item to be opened for extension and be closed for modification. Like why would something be opened and be closed at the same time? You are probably wondering why that statement sounds like a contradiction. The open-closed principle states that software entities (classes, modules, functions, and so on) should be open for extension, but closed for modification.
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |